计算数据帧上的每日回报/增量



因此,我想要计算日收益/增量的一些时间序列数据,其中,日增量=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:]只有三个值(dataframe),那么为什么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

那么,只有两列的除法何时相交:

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

方法3与方法2 的原因相同

所以问题是如何在纯熊猫身上做到这一点?我们使用shift允许您根据需要调整索引:

In [92]:
df.shift(-1)/df
Out[92]:
          0
0  2.000000
1  1.500000
2  2.333333
3       NaN

最新更新