这是数据集:
>>> df = pd.DataFrame({'id_police':['p123','p123','p123','b123','b123'],
'date':['24/01/2017','24/11/2017','25/02/2018','24/02/2018','24/03/2018'],
'prime':[0,0,10,20,30],
'prime2':[0,30,10,20,0],
})
###
id_police date prime prime2
0 p123 24/01/2017 0 0
1 p123 24/11/2017 0 30
2 p123 25/02/2018 10 10
3 b123 24/02/2018 20 20
4 b123 24/03/2018 30 0
这是我使用@Erfan的工作解决方案时得到的结果:
id_police date prime prime2 changed
0 p123 24/01/2017 0 0<- 0
1 p123 24/11/2017 0<- 30<- 1
2 p123 25/02/2018 10<- 10 1
3 b123 24/02/2018 20 20 0
4 b123 24/03/2018 30 0 0
命令:
df['changed'] = (df[['prime', 'prime2']].shift().eq(0).any(axis=1) & df[['prime', 'prime2']].ne(0).any(axis=1)).astype(int)
现在,我想将其应用于每个id_police
,例如添加groupby之类的东西……谢谢您的帮助!
答案 0 :(得分:1)
我们可以访问groupby object
中的groupid和group,然后在每次迭代中创建changed
列:
groups = []
for _, grp in df.groupby('id_police'):
grp['changes'] = (grp[['prime', 'prime2']].shift().eq(0).any(axis=1) & grp[['prime', 'prime2']].ne(0).any(axis=1)).astype(int)
groups.append(grp)
df_final = pd.concat(groups).sort_index()
哪个产量
print(df_final)
id_police date prime prime2 changes
0 p123 24/01/2017 0 0 0
1 p123 24/11/2017 0 30 1
2 p123 25/02/2018 10 10 1
3 b123 24/02/2018 20 20 0
4 b123 24/03/2018 30 0 0
如果要关闭SetCopyWarning
,请使用以下命令:
pd.options.mode.chained_assignment = None
答案 1 :(得分:1)
根据您的命令:
cols = ['prime', 'prime2']
df['changed'] = (df.groupby('id_police', sort=False, as_index=False)
.apply(lambda x: (x[cols].ne(0) & x[cols].shift(1).eq(0))
.any(axis=1).astype(int))
.reset_index(drop=True))
df
id_police date prime prime2 changed
0 p123 24/01/2017 0 0 0
1 p123 24/11/2017 0 30 1
2 p123 25/02/2018 10 10 1
3 b123 24/02/2018 20 20 0
4 b123 24/03/2018 30 0 0
将groupby
与apply
结合使用以在每个组上应用功能。并将sort=False
设置为与主df顺序相同。