0
0
PandasHow-ToBeginner · 3 min read

How to Use tail() in pandas to View Last Rows of DataFrame

In pandas, use the tail() method to view the last rows of a DataFrame or Series. By default, tail() returns the last 5 rows, but you can specify any number by passing it as an argument, like tail(3).
📐

Syntax

The tail() method syntax is simple:

  • DataFrame.tail(n=5) or Series.tail(n=5)
  • n is the number of rows to return from the end (default is 5)

This method returns the last n rows of the data.

python
DataFrame.tail(n=5)
💻

Example

This example shows how to use tail() on a pandas DataFrame to get the last 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)

# Get last 5 rows (default)
last_five = df.tail()

# Get last 3 rows
last_three = df.tail(3)

print('Last 5 rows:\n', last_five)
print('\nLast 3 rows:\n', last_three)
Output
Last 5 rows: Name Age 1 Bob 27 2 Charlie 22 3 David 32 4 Eva 29 5 Frank 25 Last 3 rows: Name Age 3 David 32 4 Eva 29 5 Frank 25
⚠️

Common Pitfalls

Common mistakes when using tail() include:

  • Passing a negative number to n, which returns an empty DataFrame.
  • Confusing tail() with head(), which returns the first rows.
  • Using tail() on an empty DataFrame, which returns an empty DataFrame without error.

Always ensure n is a non-negative integer.

python
import pandas as pd

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

# Wrong: negative number returns empty
print('tail(-2):\n', df.tail(-2))

# Right: positive number returns last rows
print('tail(2):\n', df.tail(2))
Output
tail(-2): Empty DataFrame Columns: [A] Index: [] tail(2): A 1 2 2 3
📊

Quick Reference

MethodDescriptionDefault Behavior
tail()Returns last 5 rowsReturns last 5 rows
tail(n)Returns last n rowsReturns last n rows
tail(0)Returns empty DataFrameEmpty DataFrame
tail(-n)Returns empty DataFrameEmpty DataFrame

Key Takeaways

Use tail() to quickly see the last rows of a DataFrame or Series.
By default, tail() returns 5 rows but you can specify any non-negative number.
Passing a negative number to tail() returns an empty DataFrame.
tail() works safely even on empty DataFrames without errors.
Do not confuse tail() with head(), which returns the first rows.