Difficulty: Easy | Acceptance: 93.00% | Paid: No Topics: N/A
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.
- Examples
- Constraints
- Approach 1: Using head()
- Approach 2: Using Slicing
- Approach 3: Using iloc
Examples
Example 1:
Input: DataFrame employees +-------------+--------+------------+--------+ | employee_id | name | department | salary | +-------------+--------+------------+--------+ | 3 | Bob | IT | 72000 | | 90 | Alice | Sales | 90000 | | 9 | Tatiana| Engineering| 88000 | | 60 | Ann | IT | 79000 | +-------------+--------+------------+--------+
Output: +-------------+--------+------------+--------+ | employee_id | name | department | salary | +-------------+--------+------------+--------+ | 3 | Bob | IT | 72000 | | 90 | Alice | Sales | 90000 | | 9 | Tatiana| Engineering| 88000 | +-------------+--------+------------+--------+
Explanation: The first 3 rows of the DataFrame are displayed.
Constraints
The DataFrame may have 0 or more rows.
Approach 1: Using head()
Intuition
The pandas head() method is specifically designed to return the first n rows of a DataFrame, making it the most direct and readable solution.
Steps
- Call the
head(3)method on the DataFrame to get the first 3 rows - Return the result
import pandas as pd
def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame:
return employees.head(3)Complexity
- Time: O(1) - accessing first 3 rows is constant time
- Space: O(1) - only returns a view of the original data
- Notes: Most readable and idiomatic pandas approach
Approach 2: Using Slicing
Intuition
Python slicing syntax [:3] can be used to select the first 3 rows of a DataFrame, similar to how it works with lists.
Steps
- Use slice notation
[:3]on the DataFrame - Return the sliced result
import pandas as pd
def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame:
return employees[:3]Complexity
- Time: O(1) - slicing first 3 elements is constant time
- Space: O(1) - creates a view, not a copy
- Notes: Concise Python syntax, works well for small selections
Approach 3: Using iloc
Intuition
The iloc indexer allows integer-location based indexing, providing explicit row selection by position.
Steps
- Use
iloc[0:3]to select rows at positions 0, 1, and 2 - Return the result
import pandas as pd
def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame:
return employees.iloc[0:3]Complexity
- Time: O(1) - selecting fixed number of rows
- Space: O(1) - returns a view of the data
- Notes: More explicit about integer-based indexing, useful when combined with column selection