Signup/Sign In
PUBLISHED ON: MARCH 18, 2021

Pandas DataFrame head() Method

In this tutorial, we will learn the Python pandas DataFrame.head() method. This method is used to get the first n rows of the DataFrame. This method is convenient when we want to check which type of data our object has in it. If we give negative values for 'n', this method returns all the rows except the last n rows which is equivalent to df[:-n].

The below shows the syntax of the DataFrame.head() method.

Syntax

DataFrame.head(n=5)

Parameter:

n: It represents the int, and the default value is 5 that is the number of rows to select.

Example: Getting the first n rows of the DataFrame using the DataFrame.head() Method

Here, using the DataFrame.head() method, we are getting the first 5 rows of the DataFrame. See the below example.

#importing pandas as pd
import pandas as pd
#creating the DataFrame
df= pd.DataFrame({'Language': ['Kannada','Hindi', 'Telugu', 'Tamil', 'Malyalam','Marathi','Konkani','Tulu']})
print("----First 5 rows of the DataFrame is-----")
print(df.head())

Once we run the program we will get the following output.


----First 5 rows of the DataFrame is-----
Language
0 Kannada
1 Hindi
2 Telugu
3 Tamil
4 Malyalam

Example: Specify the number of rows in the DataFrame.head() Method

We can specify the number of lines to view and here, in this example, we give n value as 2. The DataFrame.head() method returns the first 2 lines.

#importing pandas as pd
import pandas as pd
#creating the DataFrame
df= pd.DataFrame({'Language': ['Kannada','Hindi', 'Telugu', 'Tamil', 'Malyalam','Marathi','Konkani','Tulu']})
print("----First n rows of the DataFrame is-----")
print(df.head(n=2))

Once we run the program we will get the following output.


----First n rows of the DataFrame is-----
Language
0 Kannada
1 Hindi

Example: Negative value to 'n' in the DataFrame.head() Method

In this example, we give a negative value to n. For negative values of n, this method returns all rows except the last n rows, equivalent to df[:-n].

#importing pandas as pd
import pandas as pd
#creating the DataFrame
df= pd.DataFrame({'Language': ['Kannada','Hindi', 'Telugu', 'Tamil', 'Malyalam','Marathi','Konkani','Tulu']})
print("----First n rows of the DataFrame is-----")
print(df.head(-2))

Once we run the program we will get the following output.


----First n rows of the DataFrame is-----
Language
0 Kannada
1 Hindi
2 Telugu
3 Tamil
4 Malyalam
5 Marathi

Conclusion:

In this tutorial, we learned the Python pandas DataFrame.head() method. We learned the syntax and by applying this method on the DataFrame we solved examples and understood the DataFrame.head() method.



About the author:
I like writing about Python, and frameworks like Pandas, Numpy, Scikit, etc. I am still learning Python. I like sharing what I learn with others through my content.