列值更改时在另一列中记录

列值更改时在另一列中记录

我的数据框如下所示:

               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的新列crossing中通知它。当列directiondown移到up时,请执行相同的操作。我尝试了一个if语句,但是没有用……还有其他想法吗?谢谢!

最佳答案

您可以尝试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

关于python - Pandas :列值更改时在另一列中记录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54787790/

10-10 11:55