为了账号安全,请及时绑定邮箱和手机立即绑定

使用 python pandas drop 函数时显示按键错误

使用 python pandas drop 函数时显示按键错误

汪汪一只猫 2024-01-04 17:16:37
import pandas as pdimport numpy as npfrom sklearn.impute import SimpleImputerdf = pd.read_csv("Covid-19 Global Data.csv")df.head(3)      Date_reported   Country_code    Country        WHO_region     New_cases                New_deaths     0     03-01-20          AF       Afghanistan      EMRO           0                               0                                        1     04-01-20          AF       Afghanistan      EMRO           0                               0                                        2     05-01-20          AF       Afghanistan      EMRO           0                               0                                  df.drop(["Country"],axis=1,inplace=True)每次都显示按键错误。数据框构造完美,但KeyError正在弹出。
查看完整描述

3 回答

?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

该错误可能是由于列名称中存在额外的空格造成的。也许尝试添加一个空格并删除它:


df.drop(["Country "],axis=1,inplace=True)

或者


df.drop([" Country"],axis=1,inplace=True)

# df.drop([" Country "],axis=1,inplace=True)

一种更好的方法是从列名中去除多余的空格,如下所示:


df.columns = df.columns.str.strip()

df.drop(["Country"],axis=1,inplace=True)


查看完整回答
反对 回复 2024-01-04
?
喵喵时光机

TA贡献1846条经验 获得超7个赞

看来您已经删除了该Country列。

对我来说效果很好。

重新启动 karnel 并尝试再次运行它。


查看完整回答
反对 回复 2024-01-04
?
回首忆惘然

TA贡献1847条经验 获得超11个赞

使用

print(df.columns)

查看您的专栏的真实姓名。你得到了一些东西

Index(['Date_reported', 'Country_code', 'Country', 'WHO_region', 'New_cases',
       'New_deaths'],
      dtype='object')


查看完整回答
反对 回复 2024-01-04
  • 3 回答
  • 0 关注
  • 51 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信