How To Use .loc With Multiple Conditions And Groupby
I have a df thats grouped by 'Key'. I want to flag any row within a group where the discharge date matches another discharge date AND between those rows one of rows has a num1 valu
Solution 1:
You can accomplish that by using filter
.
df.loc[df.groupby(['Key','discharge']).Num1.filter(lambda x : (x.isin(num1_range).any())&(len(x)>1)).index,'flag']=1
df
Out[317]:
Key Num1 Num2 admit discharge flag
0 10003 12 121 2012-05-06 2012-05-08 1.0
1 10003 13 122 2012-05-08 2012-05-08 1.0
2 10003 13 122 2012-10-10 2012-10-12 NaN
3 10003 13 124 2012-10-10 2012-10-16 NaN
4 10003 12 125 2012-10-10 2012-10-23 NaN
5 10003 13 126 2012-11-10 2012-11-11 NaN
6 10034 16 127 2012-05-16 2012-05-20 NaN
7 10034 13 128 2012-05-20 2012-05-20 NaN
Post a Comment for "How To Use .loc With Multiple Conditions And Groupby"