gpt4 book ai didi

python - 计算数据框的每日返回/增量

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

所以我想计算每日返回/增量的一些时间序列数据,其中每日增量 = value_at_time(T)/value_at_time(T-1)

import pandas as pd
df=pd.DataFrame([1,2,3,7]) #Sample data frame
df[1:]
out:
0
1 2
2 3
3 7
df[:-1]
out:
0
0 1
1 2
2 3
######### Method 1
df[1:]/df[:-1]
out:
0
0 NaN
1 1
2 1
3 NaN

######### Method 2
df[1:]/df[:-1].values
out:
0
1 2.000000
2 1.500000
3 2.333333

######### Method 3
df[1:].values/df[:-1]
out:
0
0 2
1 1
2 2

我的问题是

  1. 如果 df[:-1] 和 df[1:] 只有三个值(数据框)那么为什么 Method_1 不起作用?
  2. 为什么几乎相似的方法 2 和 3 给出不同的结果?
  3. 为什么在 Method_2 中使用 .values 使其有效

最佳答案

让我们看看每个

方法 1,如果您查看切片返回的内容,您会发现索引未对齐:

In [87]:
print(df[1:])
print(df[:-1])

0
1 2
2 3
3 7
0
0 1
1 2
2 3

那么什么时候除法只有 2 列相交:

In [88]:
df[1:]/df[:-1]

Out[88]:
0
0 NaN
1 1.0
2 1.0
3 NaN

方法 2 生成一个 np 数组,它没有索引,因此除法将按预期的元素顺序执行:

In [89]:
df[:-1].values

Out[89]:
array([[1],
[2],
[3]], dtype=int64)

给予:

In [90]:
df[1:]/df[:-1].values

Out[90]:
0
1 2.000000
2 1.500000
3 2.333333

方法三与方法二同理

所以问题是如何在纯 pandas 中做到这一点?我们使用 shift允许您根据需要对齐索引:

In [92]:
df.shift(-1)/df

Out[92]:
0
0 2.000000
1 1.500000
2 2.333333
3 NaN

关于python - 计算数据框的每日返回/增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36572960/

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