简体   繁体   中英

Pandas: note in another column when a column value changes

My dataframe looks like this:

               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

What I need to do is when the column direction goes from the value up to down notifies it in a new column event with the value crossing . And do the same when the column direction goes from down to up . I tried with an if statement but did not work... any other idea? Thanks!

You can try DataFrame.Series.shift and np.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

You can add any other value if it's not crossing:

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

As you have multiple conditions use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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