Python Pandas if column id value greater

Viewed 90

I have what i think is a simple quesiton, but I am not sure how to implement. I have the following dataframe:

ID    Value
1     100
2     250
3     300
4     400
5     600
7     800

I would like to look at 2 id's: 3 & 5 and then drop the one with the lower value. So i am assuming I would use something like the following code, but again, i am not sure how to implement,nor am i sure how to utilize the inequality to point towards the value while directing my function at a very specific pair of id's.

def ChooseGreater(x):
    if df['id'] == 3 > df['id'] ==5
        return del df['id']==5
    else:
        return del df['id']==3

Thank you!

4 Answers

I think you can do:

df.drop(df.loc[df.ID.isin([3,5]),'Value'].idxmin(), inplace=True)

Using Python's min

df.drop(min(df.query('ID in [3, 5]').index, key=df.Value.get))

   ID  Value
0   1    100
1   2    250
3   4    400
4   5    600
5   7    800

groupby and tail

df.sort_values('Value').groupby(df.ID.replace({3: 5})).tail(1)

   ID  Value
0   1    100
1   2    250
3   4    400
4   5    600
5   7    800

You can calculate idxmin and then use np.in1d with pd.DataFrame.loc:

idx = df.loc[df['ID'].isin([3,5]), 'Value'].idxmin()
res = df.loc[~np.in1d(df.index, idx)]

print(res)

   ID  Value
0   1    100
1   2    250
3   4    400
4   5    600
5   7    800

This is method from groupby

df.loc[df.Value.groupby((~df.ID.isin([3,5])).sort_values().cumsum()).idxmax()].sort_index()
Out[167]: 
   ID  Value
0   1    100
1   2    250
3   4    400
4   5    600
5   7    800
Related