在熊猫中获取keyerror:0

时间:2020-08-11 04:50:40

标签: pandas numpy dataframe nan keyerror

在此数据中添加了一个新列,该列中的值与其他列不同。即使我不访问数据集中不存在的值,运行此代码时也会显示keyerror:0。

   df['Action']=np.nan
   for i in range(len(df)-1):
        if df['Close Price'][i] < df['Close Price'][i+1]:
            df['Action'][i] = 1
        elif df['Close Price'][i] >= df['Close Price'][i+1]:
            df['Action'][i] = -1
    df = df.dropna()
    df

如果df ['Close Price'] [i]

1 个答案:

答案 0 :(得分:1)

这不是正确的方法 df['Close Price'][i] < df['Close Price'][i+1]: 在熊猫中获取特定列的第i行值 做

if df['Close Price'].iloc[i]< df['Close Price'].iloc[i+1] :