按索引调用列时出现python数据框键错误

时间:2017-12-09 09:42:25

标签: python-3.x pandas

subset = df[['country', 'continent', 'year']]
subset.head()

此代码工作正常,但

subset = df[[1, 2, 3]]

给我一​​个错误

KeyError: '[1 2 3] not in index'

1 个答案:

答案 0 :(得分:0)

如果您想通过索引获取列,请尝试:

subset = df.iloc[:,[1, 2, 3]]

或使用df.columns并按上述方式传递列表。

subset = df[df.columns[[1, 2, 3]]]

假设您的专栏country位于1列索引。