DataFrame: employees
+-------------+--------+
| Column Name | Type |
+-------------+--------+
| employee_id | int |
| name | object |
| department | object |
| salary | int |
+-------------+--------+
Write a solution to display the first 3 rows of this DataFrame.
Example 1:
Input: DataFrame employees +-------------+-----------+-----------------------+--------+ | employee_id | name | department | salary | +-------------+-----------+-----------------------+--------+ | 3 | Bob | Operations | 48675 | | 90 | Alice | Sales | 11096 | | 9 | Tatiana | Engineering | 33805 | | 60 | Annabelle | InformationTechnology | 37678 | | 49 | Jonathan | HumanResources | 23793 | | 43 | Khaled | Administration | 40454 | +-------------+-----------+-----------------------+--------+ Output: +-------------+---------+-------------+--------+ | employee_id | name | department | salary | +-------------+---------+-------------+--------+ | 3 | Bob | Operations | 48675 | | 90 | Alice | Sales | 11096 | | 9 | Tatiana | Engineering | 33805 | +-------------+---------+-------------+--------+ Explanation: Only the first 3 rows are displayed.
Most data manipulation libraries provide a direct method to access the top few rows of a DataFrame. This approach utilizes the built-in method to fetch the first three rows efficiently.
Using Pandas in Python, the head function allows us to grab the first few rows of the DataFrame. By default, it retrieves 5 rows, but you can specify the number, in this case, 3.
JavaScript
Time Complexity: O(1), since it directly accesses the specified rows.
Space Complexity: O(1), no additional space usage beyond the output.
This approach involves manually iterating over the DataFrame and extracting the first three rows. It's useful in languages or environments where built-in functionality might not exist.
This C++ solution manually iterates through the rows of a DataFrame using a for loop. We ensure to only access rows as long as they exist, preventing out-of-bound errors.
Java
Time Complexity: O(1), since we only loop through a fixed number of rows.
Space Complexity: O(1), as we only store a constant number of rows.
| Approach | Complexity |
|---|---|
| Using Built-in Methods for DataFrames | Time Complexity: O(1), since it directly accesses the specified rows. |
| Manual Iteration | Time Complexity: O(1), since we only loop through a fixed number of rows. |
2879. Display the First Three Rows | LeetCode | Python | Pandas • You Data And AI • 701 views views
Watch 9 more video solutions →Practice Display the First Three Rows with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor