Get First N Rows of DataFrame
To get the first N rows of a DataFrame in Pandas, call head() method on this DataFrame and pass the integer value representing the number of rows, N.
By default, head() method returns first five rows of the DataFrame.
In this tutorial, we will learn the syntax of DataFrame.head() method and to use this method to get the first N rows of this DataFrame.
Syntax
The syntax of pandas DataFrame.head() method is
DataFrame.head(n=5)
where
Parameter | Value | Description |
---|---|---|
n | int. default value is 5. | Number of rows to select from this DataFrame. |
Return Value
DataFrame.
Examples
Get First Five Rows of DataFrame
If we do not pass any integer value as argument to head() method, the method returns the first five rows.
In the following program, we take a DataFrame, and get the first five rows of it using head() method.
Example.py
import pandas as pd
data = {'col_1': [10, 15, 20, 25, 30, 35, 40], 'col_2': [45, 50, 55, 60, 65, 70, 75]}
df = pd.DataFrame(data)
result = df.head()
print('Original DataFrame')
print(df)
print('\nFirst Five Rows of DataFrame')
print(result)
Output
Original DataFrame
col_1 col_2
0 10 45
1 15 50
2 20 55
3 25 60
4 30 65
5 35 70
6 40 75
First Five Rows of DataFrame
col_1 col_2
0 10 45
1 15 50
2 20 55
3 25 60
4 30 65
Get First Two Rows of DataFrame
Now let us get only the first two rows of DataFrame. Pass the value 2
as argument to head() method.
Example.py
import pandas as pd
data = {'col_1': [10, 15, 20, 25, 30, 35, 40], 'col_2': [45, 50, 55, 60, 65, 70, 75]}
df = pd.DataFrame(data)
result = df.head(2)
print('Original DataFrame')
print(df)
print('\nFirst Two Rows of DataFrame')
print(result)
Output
Original DataFrame
col_1 col_2
0 10 45
1 15 50
2 20 55
3 25 60
4 30 65
5 35 70
6 40 75
First Two Rows of DataFrame
col_1 col_2
0 10 45
1 15 50
Viewing the first n lines (three in this case)
DataFrame
Example.py
>>> df.head(3)
animal
0 alligator
1 bee
2 falcon
Output
Negative Value for N
If we give negative value as argument to head(), then those number of rows are removed from the tail of this DataFrame in the result.
Example.py
import pandas as pd
data = {'col_1': [10, 15, 20, 25, 30, 35, 40], 'col_2': [45, 50, 55, 60, 65, 70, 75]}
df = pd.DataFrame(data)
result = df.head(-4)
print('Original DataFrame')
print(df)
print('\Last Four Rows Removed from DataFrame')
print(result)
Output
Original DataFrame
col_1 col_2
0 10 45
1 15 50
2 20 55
3 25 60
4 30 65
5 35 70
6 40 75
\Last Four Rows Removed from DataFrame
col_1 col_2
0 10 45
1 15 50
2 20 55
Conclusion
In this Pandas Tutorial, we learned the syntax of DataFrame.head() method and how to use this method to get the first N rows of this DataFrame.