drop 2 last rows pandas in python

To drop the last 2 rows from a pandas DataFrame in Python, we can use the drop() method with axis=0 and inplace=True:

main.py
df.drop(df.tail(2).index, inplace=True)
40 chars
2 lines

Here df.tail(2) selects the last 2 rows of the DataFrame, and df.tail(2).index retrieves their index. Finally, df.drop() removes the selected rows from the original DataFrame.

Alternatively, you can also use negative indexing with .iloc:

main.py
df = df.iloc[:-2]
18 chars
2 lines

Here, df.iloc[:-2] selects all rows except the last 2 rows, and creates a new DataFrame that is assigned back to df.

related categories

gistlibby LogSnag