gpt4 book ai didi

python-3.x - 考虑到 pandas 系列中的不同索引,如何正确估计两列的百分比变化? Python相关

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

假设我有以下名为 df_trading_pair 的 df:

    Start Date           Open Price     High Price  Low Price   Close Price End Date
0 2022-07-20 08:00:00 0.19277 0.19324 0.19225 0.19324 2022-07-20 08:04:59.999
1 2022-07-20 08:05:00 0.19321 0.194 0.1932 0.19388 2022-07-20 08:09:59.999
2 2022-07-20 08:10:00 0.19387 0.195 0.19387 0.19489 2022-07-20 08:14:59.999
3 2022-07-20 08:15:00 0.19496 0.19628 0.19495 0.19626 2022-07-20 08:19:59.999
4 2022-07-20 08:20:00 0.19625 0.20406 0.19625 0.2035 2022-07-20 08:24:59.999

我一直在尝试找出一种简单的方法来获取 Open Price 列中前 4 元素与后 4 元素的百分比变化Close Price 中的 strong> 元素,所以我最终在 new_df 中得到以下输出:

 Close Price vs Open Price % change
0 0.0057
1 0.0087
2 0.0123
3 0.0438
dtype: float64

起初,我认为下面的句子应该很完美,毕竟两个数组都有 4 个元素并且包含我需要的值:

new_df["Close Price vs Open Price % change"] = (df_trading_pair["Close Price"][1:]-df_trading_pair["Open Price"][:-1])/df_trading_pair["Open Price"][:-1]

然而,那句话最终抛出了这个输出:

 Close Price vs Open Price % change
0 NaN
1 0.003468
2 0.005261
3 0.006668
4 NaN
dtype: float64

我不明白为什么,我也试过这句话:

new_df["Close Price vs Open Price % Change"] = [(y-x)/x*100 for x in df_trading_pair["Open Price"][:-1] for y in df_trading_pair["Close Price"][1:]]

在我看来这也应该完成我正在寻找的东西,但不幸的是它没有并抛出以下错误:

ValueError: Length of values (16) does not match length of index (5)

那么,我想在这里获得一些帮助,我还能做些什么才能获得所需的输出?

最佳答案

您需要使用 shift ,否则 pandas 将重新调整您的索引:

df['Close Price'].shift(-1).sub(df['Open Price']).div(df['Open Price'])[:-1]

输出:

0    0.005758
1 0.008695
2 0.012328
3 0.043804
dtype: float64

您的方法适用于 numpy 数组,因为没有索引重新对齐:

c = df['Close Price'][1:].to_numpy()
o = df['Open Price'][:-1].to_numpy()

out = (c-o)/o

输出:

array([0.00575816, 0.0086952 , 0.01232785, 0.04380386])

关于python-3.x - 考虑到 pandas 系列中的不同索引,如何正确估计两列的百分比变化? Python相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73059896/

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