0
0
Data Analysis Pythondata~5 mins

head() and tail() in Data Analysis Python

Choose your learning style9 modes available
Introduction

head() and tail() help you quickly see the first or last few rows of your data. This is useful to understand what your data looks like without looking at everything.

You want to check the first few entries in a sales dataset to verify data loading.
You want to see the last few rows of a log file to check recent events.
You want to quickly preview a large dataset without printing all rows.
You want to confirm the structure and columns of your data by looking at sample rows.
Syntax
Data Analysis Python
DataFrame.head(n=5)
DataFrame.tail(n=5)

Both methods return a new DataFrame with n rows.

If n is not given, it defaults to 5 rows.

Examples
Shows the first 5 rows of the DataFrame df.
Data Analysis Python
df.head()
Shows the first 3 rows of df.
Data Analysis Python
df.head(3)
Shows the last 5 rows of df.
Data Analysis Python
df.tail()
Shows the last 2 rows of df.
Data Analysis Python
df.tail(2)
Sample Program

This code creates a small table of people with their ages and cities. It then shows the first 3 rows and the last 2 rows using head() and tail().

Data Analysis Python
import pandas as pd

# Create a simple DataFrame
data = {'Name': ['Anna', 'Bob', 'Charlie', 'David', 'Eva', 'Frank'],
        'Age': [23, 35, 45, 32, 28, 40],
        'City': ['NY', 'LA', 'Chicago', 'Houston', 'Phoenix', 'Seattle']}
df = pd.DataFrame(data)

print('First 3 rows using head(3):')
print(df.head(3))

print('\nLast 2 rows using tail(2):')
print(df.tail(2))
OutputSuccess
Important Notes

If your DataFrame has fewer rows than n, head() or tail() will just return all rows.

These methods are very useful for quick data checks before deeper analysis.

Summary

head() shows the first few rows of your data.

tail() shows the last few rows of your data.

Both help you quickly understand your dataset's content and structure.