Pandas – head() and tail() method.

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
url="https://raw.githubusercontent.com/bprasad26/lwd/master/data/winequality-red.csv"
df = pd.read_csv(url)

# select first 5 rows of data
df.head()

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
df.head(10)

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
df[['alcohol','quality']].head()

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
alcohol.head()

(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
df.tail()

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
alcohol.tail(4)

Rating: 1 out of 5.

Leave a Reply