Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If dataframe.tail(1) is X, do something

Tags:

python

pandas

I am trying to check if the last cell in a pandas data-frame column contains a 1 or a 2 (these are the only options). If it is a 1, I would like to delete the whole row, if it is a 2 however I would like to keep it.

import pandas as pd

df1 = pd.DataFrame({'number':[1,2,1,2,1], 'name': ['bill','mary','john','sarah','tom']})
df2 = pd.DataFrame({'number':[1,2,1,2,1,2], 'name': ['bill','mary','john','sarah','tom','sam']})

In the above example I would want to delete the last row of df1 (so the final row is 'sarah'), however in df2 I would want to keep it exactly as it is.

So far, I have thought to try the following but I am getting an error

if df1['number'].tail(1) == 1:
    df = df.drop(-1)
like image 335
cookie1986 Avatar asked Oct 29 '25 00:10

cookie1986


1 Answers

DataFrame.drop removes rows based on labels (the actual values of the indices). While it is possible to do with df1.drop(df1.index[-1]) this is problematic with a duplicated index. The last row can be selected with iloc, or a single value with .iat

if df1['number'].iat[-1] == 1:
    df1 = df1.iloc[:-1, :]
like image 112
ALollz Avatar answered Oct 31 '25 15:10

ALollz