python - 使用 python pandas drop 函数时显示 Keyerror
问题描述
import pandas as pd
import numpy as np
from sklearn.impute import SimpleImputer
df = 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。数据框构造完美,但KeyError
正在弹出。
解决方案
该错误可能是由于列名中的额外空格造成的。也许尝试添加一个空格并删除它:
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)
推荐阅读
- push-notification - Gatsby + Netlify 添加推送通知
- python - 如何创建两个注册系统?
- angular - 带有@Host参数的单元测试Angular 9组件无法解析参数
- azure-data-factory - 如何调试 DataFlow 异常
- django - 我在哪里可以保存可重用应用程序的设置数据
- azure-cognitive-search - 将 Azure SQL DB 数据自动同步到 Azure 搜索索引
- python - 为什么我不能在 tkinter 画布中绘制 numpy 矩阵?
- android - 如何旋转 TextView 而不仅仅是它的文本
- javascript - 控制台错误无法解构“el.position(...)”的属性“top”,因为它未定义。WordPress jQuery
- java - 在 Netty 中,我想验证证书是否由 CA 颁发