Home > Blockchain >  How to fix keyerror of [] not found in axis while dropping columns, how to fix this with pandas?
How to fix keyerror of [] not found in axis while dropping columns, how to fix this with pandas?

Time:06-28

I used drop method and used

df.drop(['unnamed: 31','short name'], axis=1, inplace=True)

and I get the following key error

"['unnamed: 31' 'short name'] not found in axis".

why it is so when I define axis as well.

CodePudding user response:

  • the column you're looking for mightn't be available in columns or you might have missed whitespace or anything. first, get the columns df.columns and try copy-pasting hopefully will work

CodePudding user response:

Put a check on column list to see if they exist in dataframe or not. Here is the snippet for doing this

# Create a dataframe
df = pd.DataFrame({"A" :[1,2,3],"B" :[343,32,232]})

# Get list of columns of df
COLUMNS = df.columns.values

# Define columns you want to delete, in your case it
COLUMNS_TO_DELETE = ["B","C","D"]

# Delete only those columns which are present in dataframe
COLUMNS_TO_DELETE = [col for col in COLUMNS_TO_DELETE if col in COLUMNS]

# Apply df.drop method
df.drop(columns=COLUMNS_TO_DELETE,axis=1)
  • Related