Pandas DataFrame - head() function
The Pandas DataFrame head() function returns the first n rows of the dataframe. The syntax for using this function is given below:
Syntax
DataFrame.head(n)
Parameters
n |
Required. Specify number of rows to select. |
Return Value
Returns the first n rows of the dataframe.
Example:
In the example below, a DataFrame df is created. The head() function returns first selected number of rows of the dataframe.
import pandas as pd import numpy as np df = pd.DataFrame({ "Bonus": [5, 3, 2, 4, 3, 4], "Last Salary": [58, 60, 63, 57, 62, 59], "Salary": [60, 62, 65, 59, 63, 62]}, index= ["John", "Marry", "Sam", "Jo", "Ramesh", "Kim"] ) print("The DataFrame is:") print(df) #returning first two rows of the dataframe print("\ndf.head(2) returns:") print(df.head(2))
The output of the above code will be:
The DataFrame is: Bonus Last Salary Salary John 5 58 60 Marry 3 60 62 Sam 2 63 65 Jo 4 57 59 Ramesh 3 62 63 Kim 4 59 62 df.head(2) returns: Bonus Last Salary Salary John 5 58 60 Marry 3 60 62
Example:
n can take negative values as Python supports negative indexing. Consider the following example.
import pandas as pd import numpy as np df = pd.DataFrame({ "Bonus": [5, 3, 2, 4, 3, 4], "Last Salary": [58, 60, 63, 57, 62, 59], "Salary": [60, 62, 65, 59, 63, 62]}, index= ["John", "Marry", "Sam", "Jo", "Ramesh", "Kim"] ) print("The DataFrame is:") print(df) #using negative indexing with the dataframe print("\ndf.head(-2) returns:") print(df.head(-2))
The output of the above code will be:
The DataFrame is: Bonus Last Salary Salary John 5 58 60 Marry 3 60 62 Sam 2 63 65 Jo 4 57 59 Ramesh 3 62 63 Kim 4 59 62 df.head(-2) returns: Bonus Last Salary Salary John 5 58 60 Marry 3 60 62 Sam 2 63 65 Jo 4 57 59
❮ Pandas DataFrame - Functions