Dataframe:比较列值和下面的一行

问题描述 投票:1回答:2

我有一个指示方向的数据框:

        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.否则,将其设置为“ None”

换句话说,一旦您达到“向上”状态,它应该一直保持这种状态,直到您按下“向下”为止

结果应类似于:

        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

是否有一种无需使用循环即可完成此操作的方法?

python pandas dataframe np
2个回答
2
投票

由新数据编辑的答案首先回填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和链接的布尔掩码比较移位后的值,并按位或将numpy.where用作原始值:

|

2
投票

这里是一种方法。我会在喝咖啡后尝试改善它。

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
© www.soinside.com 2019 - 2024. All rights reserved.