首页 > 解决方案 > 我想将一列的元素复制到另一列,但跳过一个元素并忽略最后一个元素,因为它会产生错误

问题描述

for i in range(len(nifty['Pivot'])):
  nifty.p[i] = nifty.Pivot[i+1]

我想跳过最后一个元素并希望将 p 的第一个元素保留为空元素错误:

ValueError: 200 is not in range

The above exception was the direct cause of the following exception:


KeyError: 200

标签: pandasfor-loopdata-science

解决方案


那是你的错误Pivot[i+1],说如果len(nifty['Pivot'])=200然后在i=199, i+1=200, 并且nifty.Pivot[200]将失败,因为允许的最大索引是199(Python 被0索引)

我想你想要nifty['p'] = nifty['Pivot'].shift(-1)


推荐阅读