0
0
Pandasdata~5 mins

head() and tail() for previewing in Pandas

Choose your learning style9 modes available
Introduction

These functions help you quickly see the first or last few rows of your data. This is useful to understand what your data looks like without loading everything.

You want to check the first few entries of a large dataset to understand its structure.
You want to see the last few records to verify recent data entries.
You want to quickly preview data after loading it from a file.
You want to check if data cleaning steps worked by looking at sample rows.
You want to confirm column names and data types by viewing a small part of the data.
Syntax
Pandas
DataFrame.head(n=5)
DataFrame.tail(n=5)

n is the number of rows to show. Default is 5.

head() shows rows from the start, tail() shows rows from the end.

Examples
Show first 5 rows and last 5 rows of the DataFrame df.
Pandas
df.head()
df.tail()
Show first 3 rows and last 2 rows of df.
Pandas
df.head(3)
df.tail(2)
Show empty DataFrame structure with columns but no rows.
Pandas
df.head(0)
df.tail(0)
Sample Program

This code creates a small table of people with their ages and cities. Then it shows the first 3 rows and last 2 rows to preview the data.

Pandas
import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva', 'Frank'],
        'Age': [25, 30, 35, 40, 45, 50],
        'City': ['NY', 'LA', 'Chicago', 'Houston', 'Phoenix', 'Seattle']}
df = pd.DataFrame(data)

# Preview first 3 rows
print('First 3 rows:')
print(df.head(3))

# Preview last 2 rows
print('\nLast 2 rows:')
print(df.tail(2))
OutputSuccess
Important Notes

If you ask for more rows than exist, head() or tail() will just return all rows without error.

These functions do not change your data; they only show a small part for quick checks.

Summary

head() shows the first few rows of data.

tail() shows the last few rows of data.

Both help you quickly understand your dataset without loading everything.