假设我有以下称为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列中the first 4个元素相对于Close Price列中the last 4个元素的百分比变化,因此我最终在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相关问答推荐

如何翻转以列形式给出的日期间隔并提取多个重叠时段内每小时的音量?

DuckDB:带有嵌套对象的星形表达式

Python将类实例变量转换为嵌套 struct

Python避免捕获特定异常

使用数据库将文件从Sharepoint下载到文件系统

AddMultplicationEquality() 用于多个变量

匹配语句NaN

在REPLACE INTO中引用变量会抛出sqlite3.OperationalError

Python (pandas) - 判断一个 df 中的值是否在另一个(不相等)df 中的任何对之间

缺失时推断的数据类可选字段

Python ** 用于负数

无法使用 Python 和 Selenium 检索 href 属性

如何查找 tensorflow.python.data.ops.dataset_ops.MapDataset 对象的大小或形状,make_csv_dataset 的输出

基本 Flask 应用程序未运行(TypeError:模块中缺少必填字段type_ignores)

获取嵌套字典的所有键

Python 解包运算符 (*)

作为函数对象属性的 __kwdefaults__ 有什么用?

如何在不使用 @hydra.main() 的情况下获取 Hydra 配置

如何使用 d.items() 更改 for 循环中的所有字典键?

如何为 anaconda python3 安装 gi 模块?