2
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) 

Showing keyerror everytime. The dataframe is constructed perfectly but KeyError is popping up.

3 Answers 3

1

The error could be due to the additional whitespace in the column name. Perhaps try adding a whitespace and dropping it:

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

Or

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

One better way would be strip extra whitespace from the column names with the following:

df.columns = df.columns.str.strip() df.drop(["Country"],axis=1,inplace=True) 
Sign up to request clarification or add additional context in comments.

Comments

1

Seems like you have already dropped the Country column.

Worked well for me.

Restart the karnel and try to run it again.

2 Comments

No i didn't drop any of the columns of the data frame. The code is not working for any of the columns even after restarting the kernel
Then check the whitespace of the Country name. Like ' Country' or 'Country '
1

Use

print(df.columns) 

to see real names of your columns. You obtained something as

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.