我想用0或1更新列,其中对于每个empID,月份是最小的,而Sal Hike是Max: 我已经编写了代码以查找每位员工的Min Month和Max Sal Hike。
df.sort_values(['salhike','month'],ascending=[False,True]).groupby("empid").head(1)
如何用1 col'n在“是或否”中更新此内容?
输入DF:
empid age salhike month YES_or_NO
123 23 12 1 0
123 23 24 2 0
123 23 87 3 0
123 23 35 4 0
111 23 87 1 0
111 23 35 2 0
111 23 14 3 0
111 23 12 4 0
我试图获取输出表是:
empid age salhike month YES_or_NO
123 23 12 1 0
123 23 24 2 0
123 23 87 3 1
123 23 35 4 0
111 23 87 1 1
111 23 35 2 0
111 23 14 3 0
111 23 12 4 0
答案 0 :(得分:4)
尝试使用sort_values
,然后使用duplicated
和empid上的子集,将布尔序列转换为整数,并将assign
转换回数据帧中的列:
df.assign(是或否=(〜df.sort_values(['empid','salhike']))
.duplicated(subset ='empid',keep ='last'))。astype(int))
df.assign(YES_or_NO = (~df.sort_values(['salhike','month'],
ascending=['True','False','False'])
.duplicated(subset='empid', keep='last')).astype(int))
输出:
empid age salhike month YES_or_NO
0 123 23 12 1 0
1 123 23 24 2 0
2 123 23 87 3 1
3 123 23 35 4 0
4 111 23 87 1 1
5 111 23 35 2 0
6 111 23 14 3 0
7 111 23 12 4 0
答案 1 :(得分:3)
使用groupby
transform
max
df['YES_or_NO']=df.salhike.eq(df.groupby('empid')['salhike'].transform('max')).astype(int)
df
Out[380]:
empid age salhike month YES_or_NO
0 123 23 12 1 0
1 123 23 24 2 0
2 123 23 87 3 1
3 123 23 35 4 0
4 111 23 87 1 1
5 111 23 35 2 0
6 111 23 14 3 0
7 111 23 12 4 0
更新
df['YES_or_NO']=0
df.loc[df.groupby('empid')['salhike'].idxmax(),'YES_or_NO']=1