0
0
PandasHow-ToBeginner · 3 min read

How to Select Last n Rows in pandas DataFrame

To select the last n rows in a pandas DataFrame, use the tail(n) method. This returns the last n rows as a new DataFrame.
📐

Syntax

The basic syntax to select the last n rows from a pandas DataFrame is:

  • DataFrame.tail(n): Returns the last n rows.

Here, DataFrame is your data table, and n is the number of rows you want from the end.

python
DataFrame.tail(n)
💻

Example

This example shows how to create a simple DataFrame and select the last 3 rows using tail(3).

python
import pandas as pd

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

last_three = df.tail(3)
print(last_three)
Output
Name Age 2 Charlie 22 3 David 32 4 Eva 29
⚠️

Common Pitfalls

One common mistake is using head(n) instead of tail(n) when you want the last rows. Another is forgetting that tail() returns a new DataFrame and does not modify the original.

Also, if n is larger than the number of rows, tail(n) returns the entire DataFrame without error.

python
import pandas as pd

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

# Wrong: using head to get last rows
wrong = df.head(2)

# Right: using tail to get last rows
right = df.tail(2)

print('Wrong (head):\n', wrong)
print('Right (tail):\n', right)
Output
Wrong (head): A 0 1 1 2 Right (tail): A 1 2 2 3
📊

Quick Reference

MethodDescription
DataFrame.tail(n)Returns last n rows of the DataFrame
DataFrame.head(n)Returns first n rows (not for last rows)
DataFrame.iloc[-n:]Alternative to tail, selects last n rows by position

Key Takeaways

Use DataFrame.tail(n) to get the last n rows easily.
tail(n) returns a new DataFrame and does not change the original.
If n is larger than the DataFrame length, tail(n) returns all rows.
Avoid confusing tail(n) with head(n), which returns first rows.
You can also use DataFrame.iloc[-n:] as an alternative.