0
0
PandasHow-ToBeginner · 3 min read

How to Use head() in pandas to View Data Samples

Use the head() method in pandas to view the first few rows of a DataFrame. By default, head() shows the first 5 rows, but you can specify a number inside the parentheses to see more or fewer rows.
📐

Syntax

The head() method is called on a pandas DataFrame or Series to return the first n rows.

  • df.head(): Returns the first 5 rows by default.
  • df.head(n): Returns the first n rows, where n is an integer you specify.
python
df.head(n=5)
💻

Example

This example shows how to create a simple DataFrame and use head() to view its first rows. It demonstrates the default behavior and how to specify a different number of rows.

python
import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva', 'Frank'],
        'Age': [24, 27, 22, 32, 29, 25]}
df = pd.DataFrame(data)

# Default: first 5 rows
print(df.head())

# First 3 rows
print(df.head(3))
Output
Name Age 0 Alice 24 1 Bob 27 2 Charlie 22 3 David 32 4 Eva 29 Name Age 0 Alice 24 1 Bob 27 2 Charlie 22
⚠️

Common Pitfalls

Some common mistakes when using head() include:

  • Passing a non-integer value as the number of rows, which causes an error.
  • Expecting head() to modify the DataFrame; it only returns a view and does not change the original data.
  • Using head() on an empty DataFrame returns an empty DataFrame without error.
python
import pandas as pd

data = {'A': [1, 2, 3]}
df = pd.DataFrame(data)

# Wrong: passing a string causes error
# df.head('3')  # This will raise a TypeError

# Correct usage
print(df.head(2))
Output
A 0 1 1 2
📊

Quick Reference

UsageDescription
df.head()Returns first 5 rows of DataFrame
df.head(n)Returns first n rows, where n is an integer
df.head(0)Returns an empty DataFrame with columns only
df.head(-1)Returns all rows except the last one (negative values allowed)

Key Takeaways

Use df.head() to quickly see the first 5 rows of your data.
Specify a number inside head(n) to see a different number of rows.
head() does not change your data; it only shows a preview.
Passing non-integers to head() causes errors, so use integers only.
head(0) returns an empty DataFrame with column headers.