Dataframe:比较列值和一行b

2024-09-27 22:22:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带方向的数据框:

        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

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

有没有不使用循环的方法来完成这个任务?你知道吗


Tags: 数据方法none状态方向条件动量direction
2条回答

由新数据编辑的答案首先填充None值,然后将Downward替换为None

#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

旧答案:

^{}与链式布尔掩码一起使用,比较移位值,并将原始值按|用于按位或:

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

这里有一个方法。喝点咖啡后我会努力改进的。。。你知道吗

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

相关问题 更多 >

    热门问题