python - 从范围中的每个第 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 对象,所以这不起作用。我应该如何更改代码以使其工作?谢谢。
解决方案
您的索引是 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
推荐阅读
- javascript - 如何使用提交输入按钮作为当前选项卡中另一个网页的链接?
- firebase - 要链接到电子邮件的 Firebase 匿名用户
- reactjs - 如何确保在 react-redux 中调用 componentDidMount() 之前返回更新的状态?
- php - 如何请求获取价值?
- java - 在 swing 中为 JTable 设置默认排序列
- javascript - 如何在 es6 中运行 nodejs child_process?
- javascript - 从 Javascript (nodeJS) 到 dart (Flutter) 以及从 dart 到 Javascript 的加密和解密
- python - Python 日志记录模块平台差异:OSX 与 Linux
- php - array_udiff 不应该为我的两个数组的每次迭代调用我的函数吗?
- r - 具有更改索引大小的嵌套 foreach