首页 > 解决方案 > 从范围中的每个第 n 个元素在 Dataframe 中创建新列

问题描述

我正在尝试在数据框中构造一个新列,该列是不同列中元素的乘积。问题是它必须是每五个元素,并且必须是我们现在所在索引的前 52 个元素。为了解释它,我需要索引为 1,6,11,16 ... 262 的列 A 的乘积位于新列的第一个索引下。下一个将是索引 2,7,12,17 ... 263 等的乘积。这就是我尝试将其编码为的内容。

for i,r in df.iterrows():
     df["Rolling_Return"] = df.iloc[i:262+i:5,:].product

问题是我的索引是 DateTime 对象,所以这不起作用。我应该如何更改代码以使其工作?谢谢。

标签: pythonpandasdataframe

解决方案


您的索引是 DateTime 对象,因此您可以重置索引:

df.reset_index(inplace=True) # To insert index into 'index' column and create new index

for i,r in df.iterrows():
   df["Rolling_Return"] = df.iloc[i:262+i:5,:].product

df.set_index('index', inplace=True) # To set your dataframe index using 'index' column which is your old index

推荐阅读