我有一个数据框:
Date_1 Date_2 is_B weight_1
01/09/2019 02/08/2019 1 254
01/09/2019 02/08/2019 1 320
01/09/2019 04/08/2019 1 244
01/09/2019 04/08/2019 1 247
01/09/2019 14/08/2019 0 343
01/09/2019 14/08/2019 1 161
01/09/2019 14/08/2019 1 386
01/09/2019 15/08/2019 1 465
01/09/2019 15/08/2019 1 133
01/09/2019 15/08/2019 1 310
01/09/2019 15/08/2019 1 155
我想生成一列new_weight,以便对于每个date_1,new_weight的值为5000-weight_1,其中is_B值为1。如果is_B = 0,则将较旧的new_weight值复制到new_weight中。
我知道要计算new_weight,我们可以做到:
df = 5000 - df.groupby('date_1')['weight_1'].cumsum()
但是我不确定如何在代码中为is_b应用条件。
有人可以建议用熊猫或麻木的方式做同样的事情吗?
编辑
预期产量
Date_1 Date_2 is_B weight_1 new_weight
01/09/2019 02/08/2019 1 254 5000-254
01/09/2019 02/08/2019 1 320 5000-254-320
01/09/2019 04/08/2019 1 244 5000-254-320-244
01/09/2019 04/08/2019 1 247 5000-254-320-244-247
01/09/2019 14/08/2019 0 343 5000-254-320-244-247(we won't subtract 343 as isBooked = 0)
01/09/2019 14/08/2019 1 161 .
01/09/2019 14/08/2019 1 386 .
01/09/2019 15/08/2019 1 465 .
01/09/2019 15/08/2019 1 133 .
01/09/2019 15/08/2019 1 310 .
01/09/2019 15/08/2019 1 155 .
谢谢
您可以使用DataFrame.mask
+ Series.cumsum
:
df['new_weight']=5000-(df.mask(df['is_B'].eq(0)).groupby('Date_1')['weight_1'].cumsum()).ffill()
print(df)
Date_1 Date_2 is_B weight_1 new_weight
0 01/09/2019 02/08/2019 1 254 4746.0
1 01/09/2019 02/08/2019 1 320 4426.0
2 01/09/2019 04/08/2019 1 244 4182.0
3 01/09/2019 04/08/2019 1 247 3935.0
4 01/09/2019 14/08/2019 0 343 3935.0
5 01/09/2019 14/08/2019 1 161 3774.0
6 01/09/2019 14/08/2019 1 386 3388.0
7 01/09/2019 15/08/2019 1 465 2923.0
8 01/09/2019 15/08/2019 1 133 2790.0
9 01/09/2019 15/08/2019 1 310 2480.0
10 01/09/2019 15/08/2019 1 155 2325.0
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句