head() and tail() (Pandas)

df.head(n) returns the first n rows of a DataFrame or Series and df.tail(n) returns the last n; both default to 5. They are the quickest way to peek at data without printing the whole object.

Pandas

When you load a dataset the first thing you usually do is call head() to confirm the columns, the header, and a few sample values look right. tail() is just as useful for checking the end of time-ordered data or spotting trailing junk rows.

Both accept a negative argument: head(-2) returns everything except the last two rows, and tail(-2) returns everything except the first two. They return a view-like copy, so they are cheap and never modify the original.

These methods are the standard alternative to printing a giant frame, which pandas would otherwise truncate anyway based on display options.

Syntax

df.head(n=5)  |  df.tail(n=5)

Examples

Python

import pandas as pd
df = pd.DataFrame({"n": range(5)})
print(df.tail(2))

Output:

   n
3  3
4  4

Learn it in a lesson

See also

Back to the Dictionary