【问题标题】:Frustrating error: Throwing KeyError when creating new columns in Pandas令人沮丧的错误:在 Pandas 中创建新列时抛出 KeyError
【发布时间】:2020-12-07 17:12:52
【问题描述】:

这很奇怪,我以前用过这段代码,它有效。但现在它给我一个 KeyError 说:

KeyError:“[Index(['0', '1'], dtype='object')] 中没有一个 [列]"

d = {'col1': [1, 2, 3], 'col2': [3, 4, 5]}
df = pd.DataFrame(data=d)
df[[str(c) for c in range(2)]] = [[5,6],[6,6], [7,7]]

我什至让我的朋友在他身边测试它,他执行代码没有任何错误没有任何问题。还有,我的Pandas版本确实不一样,一个是1.1.4,一个是1.0.3。

另外,如果有人使用.loc.iloc 有一个优雅的解决方案,请告诉我。当版本控制不是问题时,为什么这在我的计算机上不起作用,我真的很沮丧。

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    对我来说工作得很好。

    另一种解决方案是创建新的 DataFrame 并添加到原来的:

    df = df.join(pd.DataFrame([[5,6],[6,6], [7,7]], index=df.index, columns=['0','1']))
    print (df)
       col1  col2  0  1
    0     1     3  5  6
    1     2     4  6  6
    2     3     5  7  7
    

    【讨论】:

      猜你喜欢
      • 2011-04-03
      • 1970-01-01
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-17
      相关资源
      最近更新 更多