如何解决 KeyError(f"None of [key] are in the [axis_name]") 在这种情况下(Pandas)?

Posted

技术标签:

【中文标题】如何解决 KeyError(f"None of [key] are in the [axis_name]") 在这种情况下(Pandas)?【英文标题】:How to solve KeyError(f"None of [key] are in the [axis_name]") in this case (Pandas)?如何解决 KeyError(f"None of [key] are in the [axis_name]") 在这种情况下(Pandas)? 【发布时间】:2021-04-01 22:55:55 【问题描述】:

我有一个 CSV 文件,例如:

id name email physics chemistry maths
1 Sta sta@example.com 67 78 90
2 Danny dany@example.com 77 98 89
3 Elle elle@example.com 77 67 90

现在我想使用具有新列的 pandas 输出一个新的 CSV 文件,例如:

id name grade address physics chemistry attendance maths total

我想在随机位置创建新列,我想在新列中将值设置为空白。

我尝试过使用:

import pandas as pd

df = pd.read_csv("sample.csv")
final_df = df.loc[['id','name','grade','address','physics','chemistry','attendance','maths','total']]

当我这样做时,我得到了一个错误:

KeyError(f“None of [key] are in the [axis_name]”)

任何安排这个的想法或建议。

【问题讨论】:

【参考方案1】:

假设您已经拥有数据框,我们使用您提供的代码:

import pandas as pd

df = pd.read_csv("sample.csv")

您的额外列应存储在列表中,这使您的代码更易于编写和理解。

additional_cols = ['grade','address','attendance','total']

添加多列的最佳方法是像 U11-Forward 建议的那样重新索引。

mydf = df.reindex(df.columns.tolist() + additional_cols, axis = 1)

这里[1]提出了一个类似的问题:How to add an empty column to a dataframe?

关于您的错误,文档可以帮助您: loc 方法用于访问元素而不是创建它们。如果元素不可访问,则返回键错误。

【讨论】:

【参考方案2】:

如果您想添加新列,您应该尝试使用reindexaxis=1

import pandas as pd

df = pd.read_csv("sample.csv")
final_df = df.reindex(['id','name','grade','address','physics','chemistry','attendance','maths','total'], axis=1)

【讨论】:

以上是关于如何解决 KeyError(f"None of [key] are in the [axis_name]") 在这种情况下(Pandas)?的主要内容,如果未能解决你的问题,请参考以下文章

如何解决 KeyError:u“[Index([..], dtype='object')] 中没有 [列]”

在 Pandas 中使用 groupby 函数时如何解决“keyerror”?

python里出现keyerror 怎么解决

关于hue安装后出现KeyError: "Couldn't get user id for user hue"的解决方法

KeyError: “None of [Int64Index([...], dtype=‘int64‘, length=739)] are in the [columns]“

keras.fit_generator KeyError: '"小'