我有一个指示的数据框:
Direction:
2/01/19 None
1/31/19 Upward
1/30/19 None
1/29/19 None
1/28/19 Downward
1/27/19 None
1/26/19 None
1/25/19 Upward
我要基于以下条件(从1/25/19开始)创建“动量”列:
1.如果相应日期的方向为“向上”,则将值设置为“向上”
。2.如果动量下方的第一行是“向上”,将其设置为“向上”
。3.如果相应日期的“方向”是“向下”,则将其设置为“无”
。4.否则,将其设置为“无”。
换句话说,一旦您达到“向上”状态,就应该保持这种状态,直到您单击“向下”
结果应如下所示:
Direction: Momentum:
2/01/19 None Upward
1/31/19 Upward Upward
1/30/19 None None
1/29/19 None None
1/28/19 Downward None
1/27/19 None Upward
1/26/19 None Upward
1/25/19 Upward Upward
有没有一种方法可以不使用循环来完成?
通过新数据编辑答案,首先回填None
值,然后替换Downward
为None
s:
#first replace strings Nones to None type
df['Direction:'] = df['Direction:'].mask(df['Direction:'] == 'None', None)
df['Momentum:'] = df['Direction:'].bfill().mask(lambda x: x == 'Downward', None)
要么:
s = df['Direction:'].bfill()
df['Momentum:'] = s.mask(s == 'Downward', None)
print (df)
Direction: Momentum:
2/01/19 None Upward
1/31/19 Upward Upward
1/30/19 None None
1/29/19 None None
1/28/19 Downward None
1/27/19 None Upward
1/26/19 None Upward
1/25/19 Upward Upward
旧答案:
numpy.where
与链接的布尔掩码一起使用,比较移位后的值,也|
可以按位或使用原始值:
mask = df['Direction:'].eq('Upward') | df['Direction:'].shift(-1).eq('Upward')
df['Momentum:'] = np.where(mask, 'Upward', None)
print (df)
Direction: Momentum:
1/31/19 None Upward
1/30/19 Upward Upward
1/29/19 None None
1/28/19 None None
1/27/19 Downward None
1/26/19 None Upward
1/25/19 Upward Upward
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句