在数据帧中从一个范围中的每第n个元素创建一个新列



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

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

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

您的索引是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

相关内容

最新更新