Get Last N Rows of DataFrame – DataFrame.tail()

To get the last n rows from a DataFrame in Pandas, call tail() method on this DataFrame and pass the value for n as argument to this method.

DataFrame.tail() returns a DataFrame with last n rows from the object based on position.

If n is negative, DataFrame.tail() function returns all rows except the first n rows.

Syntax

The syntax of pandas DataFrame.tail() method is

</>
Copy
DataFrame.tail(n=5)

where

ParameterValueDescription
nint, default 5Number of rows to select.

Return Value

DataFrame.

Examples

Get Last 5 Rows of DataFrame

By default, the value of parameter n is 5 in tail().

In the following program, we take a DataFrame with seven rows, and get the last five rows using tail() method.

Example.py

</>
Copy
import pandas as pd

data = {'col_1': [10, 15, 20, 25, 30, 35, 40], 'col_2': [45, 50, 55, 60, 65, 70, 75]}
df = pd.DataFrame(data)

result = df.tail()

print(result)

Output

   col_1  col_2
2     20     55
3     25     60
4     30     65
5     35     70
6     40     75

Get Last Three Rows of DataFrame

To get last three rows of DataFrame, pass n=3 for tail() method.

Example.py

</>
Copy
import pandas as pd

data = {'col_1': [10, 15, 20, 25, 30, 35, 40], 'col_2': [45, 50, 55, 60, 65, 70, 75]}
df = pd.DataFrame(data)

result = df.tail(3)

print(result)

Output

   col_1  col_2
4     30     65
5     35     70
6     40     75

Get Last Row of DataFrame

To get the last row of DataFrame, pass n=1.

Example.py

</>
Copy
import pandas as pd

data = {'col_1': [10, 15, 20, 25, 30, 35, 40], 'col_2': [45, 50, 55, 60, 65, 70, 75]}
df = pd.DataFrame(data)

result = df.tail(1)

print(result)

Output

   col_1  col_2
6     40     75

Get All Rows Except the First n Rows of DataFrame

We can get all rows expect the first n rows, by passing a negative n to the tail() method.

In the following program, we get all rows except the first 4 rows by passing -4 for parameter n to tail() method.

Example.py

</>
Copy
import pandas as pd

data = {'col_1': [10, 15, 20, 25, 30, 35, 40], 'col_2': [45, 50, 55, 60, 65, 70, 75]}
df = pd.DataFrame(data)

result = df.tail(-4)

print(result)

Output

   col_1  col_2
4     30     65
5     35     70
6     40     75

Conclusion

In this Pandas Tutorial, we learned how to get last n rows from DataFrame using pandas DataFrame.tail() method.