繁体   English   中英

Dataframe:比较列值和下一行

[英]Dataframe: compare column value and one row below

我有一个 dataframe 指示:

        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

我想根据以下条件(从 2019 年 1 月 25 日开始)创建一个“动量”列:
1. 如果对应日期的方向为“向上”,则将值设置为“向上”
2. 如果 Momentum 中下面的第一行是“向上”,则将其设置为“向上”
3. 如果对应日期的Direction为“Downward”,则设置为“None”
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

有没有办法在不使用循环的情况下做到这一点?

这是一种方法。 喝杯咖啡后我会尝试改进它...

df['Momentum:'] = None  # Base case.
df.loc[df['Direction:'].eq('Upward'), 'Momentum:'] = 'Upward'
df.loc[df['Direction:'].eq('Downward'), 'Momentum:'] = 1  # Temporary value.
df.loc[:, 'Momentum:'] = df['Momentum:'].bfill()
df.loc[df['Momentum:'].eq(1), 'Momentum:'] = None  # Set temporary value back to None.
>>> 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

通过新数据编辑的答案首先返回填充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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM