我想获取 pandas 数据框中列的相对索引

I want to get the relative index of a column in a pandas dataframe

我想为一只股票制作一个新的第 5 天 return 专栏,比方说。我正在使用 pandas 数据框。我使用 rolling_mean 函数计算了移动平均线,但我不确定如何像在电子表格 (B6-B1) 中那样引用行。有谁知道我如何做这个索引引用和减法?

示例数据框:

day    price    5-day-return
1      10          -
2      11          -
3      15          -
4      14          -
5      12          -
6      18          i want to find this ((day 5 price) -(day 1 price) )
7      20          then continue this down the list
8      19
9      21 
10     22

你想要这个吗:

In [10]:

df['5-day-return'] = (df['price'] - df['price'].shift(5)).fillna(0)
df
Out[10]:
   day  price  5-day-return
0    1     10             0
1    2     11             0
2    3     15             0
3    4     14             0
4    5     12             0
5    6     18             8
6    7     20             9
7    8     19             4
8    9     21             7
9   10     22            10

shift returns the row at a specific offset, we use this to subtract this from the current row. fillna 填充将在第一次有效计算之前出现的 NaN 值。