【问题标题】: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}]”)

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

【问题讨论】:

    标签: python python-3.x pandas dataframe numpy


    【解决方案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)
      

      【讨论】:

        猜你喜欢
        • 2022-12-12
        • 1970-01-01
        • 2020-02-14
        • 1970-01-01
        • 2021-08-04
        • 2021-01-11
        • 1970-01-01
        • 1970-01-01
        • 2011-04-19
        相关资源
        最近更新 更多