首页 > 解决方案 > 在数据框中调用 key 返回 keyerror

问题描述

我正在尝试使用我在使用 concat 函数时分配的键来检索数据,但是它总是返回 keyerror。

例如:

lists = pd.DataFrame({ "no_1": [1,2,3,4]})
x = pd.DataFrame( {"no_2": [3,3,4,5]})
total = pd.concat([lists, x], axis=0, keys=["a", "b"])
print(total["a"])

这将返回 keyerror 'a'。它应该打印在键“a”下分配的数据。

标签: pythonpandas

解决方案


调用total["a"]尝试"a"从 dataframe中检索列total,而“a”是此处的索引(行标识符)。

要选择这样的索引,您需要改为使用total.loc["a"]


推荐阅读