gpt4 book ai didi

python - Pandas :当列值更改时在另一列中注释

转载 作者:太空宇宙 更新时间:2023-11-04 02:05:43 25 4
gpt4 key购买 nike

我的数据框是这样的:

               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 列从值 updown 时在新列 中通知它事件,值为crossing。当 direction 列从 downup 时执行相同的操作。我尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com