熊猫:列值更改时在另一列中记录

时间:2019-02-20 13:44:13

标签: python pandas

我的数据框如下:

               time                price        macd          signal     macd_histogram cross   output  direction
    49  2019-01-01 12:00:07.865 0.00225919  4.578325e-06    4.294706e-06    2.836196e-07        False   up
    50  2019-01-01 12:00:09.286 0.00226142  4.622147e-06    4.360194e-06    2.619531e-07        False   up
    51  2019-01-01 12:03:22.676 0.00225699  4.272353e-06    4.342626e-06    -7.027294e-08       False   down
    52  2019-01-01 12:05:36.318 0.00225908  4.106013e-06    4.295303e-06    -1.892901e-07       False   down
    53  2019-01-01 12:11:42.492 0.00225479  3.607286e-06    4.157700e-06    -5.504139e-07       False   down

我需要做的是,当列direction从值up变为down时在新列event中用值{{1}通知它}。当列crossingdirectiondown时,请执行相同的操作。我尝试了一个if语句,但是没有用……还有其他想法吗?谢谢!

1 个答案:

答案 0 :(得分:2)

您可以尝试DataFrame.Series.shiftnp.where

df = pd.DataFrame({'direction':['up', 'up', 'down', 'down', 'up', 'up']})
df


   direction
0   up
1   up
2   down
3   down
4   up
5   up

df['event'] = np.where(df['direction'] != df['direction'].shift(1), 'crossing', df['direction'])
df

    direction   event
0   up         crossing
1   up           up
2   down       crossing
3   down        down
4   up         crossing
5   up           up

如果不相交,则可以添加任何其他值:

df['event'] = np.where(df['direction'] != df['direction'].shift(1), 'crossing', 'no event')
df
  direction     event
0   up         crossing
1   up         no event
2   down       crossing
3   down       no event
4   up         crossing
5   up         no event

如果您有多个条件,请使用np.select

condition1 = (df['direction'] != df['direction'].shift(1)) & (df['direction'] == 'up')
condition2 = (df['direction'] != df['direction'].shift(1)) & (df['direction'] == 'down')
df['event']= np.select([condition1, condition2], ['crossing up', 'crossing down'], default='no event')
df

    direction   event
0   up       crossing up
1   up       no event
2   down    crossing down
3   down    no event
4   up      crossing up
5   up      no event