+

Python | Pandas Dataframe / Series.head () method

The Pandas head() method is used to return the first n (default 5) lines of a data frame or series.

Syntax: Dataframe.head(n=5)

Parameters:
n: integer value, number of rows to be returned

Return type: Dataframe with top n rows

To load the dataset used in the following example, press here.
In the following examples, the data frame used contains data for some NBA players. An image of the data frame before any operations is attached below. 

Example # 1:

In this example, the top 5 rows of the data frame are returned and stored in a new variable. Parameters are not passed to the .head () method, since the default is 5.

# pandas module import

import pandas as pd

 
# create data frame

data = pd.read_csv ( " https://media.python.engineering/wp-content/uploads/nba.csv " )

 
# calling the head () method
# save in a new variable

data_top data.head ()

 
# display
data_top

Output:
As shown in the output image, you can see that the index of the rows returned is in the range 0 to 4. Therefore, the first 5 were returned lines. 

Example # 2: Calling Series with the n () parameter

This example calls the .head () method on a series with user input of the n parameter to return the first 9 lines of the series.

# pandas module import

import pandas as pd

 
# create data frame

data = pd.read_csv ( " https://media.python.engineering/wp-content/uploads/nba.csv " )

  
# number of lines to return

n = 9

 
# create series

series = data [ "Name" ]

 
# return first n lines

top = series.head (n = n)

 
# display
top

Output:
As shown in the output image, the first 9 rows were returned in the range from 0 to about the 8th position of the index. 

Get Solution for free from DataCamp guru