How to Select First n Rows in pandas DataFrame
To select the first
n rows in a pandas DataFrame, use the head(n) method. This returns a new DataFrame containing only the first n rows, making it easy to preview or work with a subset of your data.Syntax
The basic syntax to select the first n rows from a pandas DataFrame is:
DataFrame.head(n): Returns the firstnrows.
Here, DataFrame is your data table, and n is the number of rows you want to select.
python
DataFrame.head(n)
Example
This example shows how to create a simple DataFrame and select the first 3 rows using head(3).
python
import pandas as pd data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'], 'Age': [25, 30, 35, 40, 45]} df = pd.DataFrame(data) first_three_rows = df.head(3) print(first_three_rows)
Output
Name Age
0 Alice 25
1 Bob 30
2 Charlie 35
Common Pitfalls
Some common mistakes when selecting the first n rows include:
- Using slicing like
df[:n]works but is less clear thanhead(n). - Forgetting that
head()returns a new DataFrame and does not modify the original. - Passing a negative number to
head()returns all rows except the lastabs(n), which can be confusing.
python
import pandas as pd data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]} df = pd.DataFrame(data) # Negative number returns all but last rows print(df.head(-1)) # Positive number to get first n rows print(df.head(2))
Output
Name Age
0 Alice 25
1 Bob 30
Name Age
0 Alice 25
1 Bob 30
Quick Reference
| Method | Description | Example |
|---|---|---|
| head(n) | Returns first n rows | df.head(5) |
| iloc[:n] | Select rows by position | df.iloc[:5] |
| slice [:n] | Python slicing for rows | df[:5] |
Key Takeaways
Use df.head(n) to select the first n rows clearly and efficiently.
head(n) returns a new DataFrame and does not change the original data.
Avoid passing negative numbers to head() unless you want all but last rows.
You can also use df.iloc[:n] or df[:n] but head(n) is more readable.
Selecting first n rows is useful for quick data previews and analysis.