Pandas – head() and tail() method.

Spread the love

Pandas head and tail method is used to select the First or Last N rows of data from a dataframe or a series.

(A) head() – select First N rows of data –

# import pandas 
import pandas as pd

# read data
df = pd.read_csv(url)

# select first 5 rows of data

By default, the head method returns first 5 rows of data. If you want to return more rows of data then use the n parameter.

# return first 10 rows of data

You can also select few rows of data for a subset of columns using the head method.

# show first 5 rows of alcohol and quality column

You can also use the head method to select first n rows of data from a series.

# create a series from df
alcohol = df['alcohol']
print("Data Type:",type(alcohol))

# select first 5 rows from a series

(B) tail() – select Last N rows of data –

To select last N rows of data, we use the tail method in pandas.

# select last 5 rows of data

By default, tail also select 5 rows of data but from the last. You can change it using the n parameter.

We can also select last n rows of data from a series.

# select last 4 rows of data from a series

Rating: 1 out of 5.

Leave a Reply