gpt4 book ai didi

python - 根据多个条件比较数据帧的一行

转载 作者:行者123 更新时间:2023-12-04 15:37:17 25 4
gpt4 key购买 nike

我的数据框是这样的:

    price        trend  decreasing  increasing  condition_decreasing
0 7610.4 no trend 0.0 False
1 7610.4 no trend 0.0 False
2 7610.4 no trend 0.0 False
3 7610.4 decreasing 7610.4 True
4 7610.4 decreasing 7610.4 False
5 7610.4 decreasing 7610.4 False
6 7610.4 decreasing 7610.4 False
7 7610.4 decreasing 7610.4 False
8 7610.4 decreasing 7610.4 False
9 7610.4 decreasing 7610.4 False
10 7610.3 no trend 0.0 True
11 7610.3 no trend 0.0 False
12 7613.9 no trend 0.0 False
13 7613.9 no trend 0.0 False
14 7613.4 no trend 0.0 False
15 7613 decreasing 7613 True
16 7612 decreasing 7612 False
17 7612 decreasing 7612 False
18 7612 no trend 7612 True

我基本上需要做的是,当 trend 列从 no trend 变为 decreasing 时,从 列中获取该值code>price 并将其与 price 列趋势从 decreasing 变为 no trend 时的列值进行比较。因此,在上面的示例中,它将比较第 3 行的值 7610.4 和第 10 行的值 7610.3。

我尝试添加一个列来指示列趋势何时发生变化,使用以下代码:condition_decreasing = (data['trend'] != data['trend'].shift(1))

但是在我不知道如何在循环中迭代数据框并比较两个价格之后......有什么想法吗?感谢您的帮助!

预期的输出将是这样的数据框:

price    trend  decreasing  increasing  condition_decreasing output
0 7610.4 no trend 0.0 False
1 7610.4 no trend 0.0 False
2 7610.4 no trend 0.0 False
3 7610.4 decreasing 7610.4 True
4 7610.4 decreasing 7610.4 False
5 7610.4 decreasing 7610.4 False
6 7610.4 decreasing 7610.4 False
7 7610.4 decreasing 7610.4 False
8 7610.4 decreasing 7610.4 False
9 7610.4 decreasing 7610.4 False
10 7610.3 no trend 0.0 True -0.1
11 7610.3 no trend 0.0 False
12 7613.9 no trend 0.0 False
13 7613.9 no trend 0.0 False
14 7613.4 no trend 0.0 False
15 7613 decreasing 7613 True
16 7612 decreasing 7612 False
17 7612 decreasing 7612 False
18 7612 no trend 7612 True -1

所以基本上是包含两个价格差的列 7610.3 - 7610.4

最佳答案

我们可以使用DataFrame.reindex计算差异后:

m=data['trend'].ne( data['trend'].shift()
.fillna(data['trend']) )
data['output']=( data.loc[m,'price'].diff()
.reindex(data.index)
.where(data['trend'].eq('no trend')) )
#.where(data['trend'].ne('decreasing')) )
#.where(data['trend'].str.replace(' ','').eq('notrend')) )

print(data)

# m is your condition_decreasing column

#data['output']=( data.loc[data['condition_decreasing'],'price']
# .diff()
# .reindex(data.index)
# .where(data['trend'].eq('no trend')) )

输出

     price            trend  decreasing_increasing  output
0 7610.4 no trend 0.0 NaN
1 7610.4 no trend 0.0 NaN
2 7610.4 no trend 0.0 NaN
3 7610.4 decreasing 7610.4 NaN
4 7610.4 decreasing 7610.4 NaN
5 7610.4 decreasing 7610.4 NaN
6 7610.4 decreasing 7610.4 NaN
7 7610.4 decreasing 7610.4 NaN
8 7610.4 decreasing 7610.4 NaN
9 7610.4 decreasing 7610.4 NaN
10 7610.3 no trend 0.0 -0.1
11 7610.3 no trend 0.0 NaN
12 7613.9 no trend 0.0 NaN

关于python - 根据多个条件比较数据帧的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59354733/

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