Pandas DataFrame - Delete rows after specific index


Pandas DataFrame - Delete rows after specific index

To delete rows after a specific index from a DataFrame, call DataFrame.truncate() function and pass the index value for the after parameter.

Syntax

The syntax to delete the rows after the index x from DataFrame df is

df.truncate(after=x)

Examples

1. Delete rows in DataFrame after index=2

In this example, we take a DataFrame with five rows, and delete the rows present after the index 2 using DataFrame.truncate() function.

Python Program

import pandas as pd

df = pd.DataFrame({'name':['a', 'b', 'c', 'd', 'e'],
                   'age' :[20, 21, 20, 19, 21]})
result = df.truncate(after=2)
print(result)

Output

  name  age
0    a   20
1    b   21
2    c   20

Summary

In this Pandas Tutorial, we learned how to delete the rows present after specific index from a DataFrame.