how to remove last row of a pandas dataframe in python

To remove the last row of a pandas DataFrame in Python, you can use the drop method along with the index parameter. Here's an example:

main.py
import pandas as pd

# Create a sample DataFrame
data = {'A': [1, 2, 3, 4],
        'B': ['a', 'b', 'c', 'd']}
df = pd.DataFrame(data)

# Remove the last row
df = df.drop(df.index[-1])

print(df)
196 chars
12 lines

This code will remove the last row of the DataFrame and assign the modified DataFrame back to df. If you want to modify the DataFrame in place without assigning it back to df, you can use the inplace parameter:

main.py
df.drop(df.index[-1], inplace=True)
36 chars
2 lines

Both methods will give you the same result, which is a DataFrame without the last row.

related categories

gistlibby LogSnag