4

I tried both:

df = df.copy() 
df.drop([' SG'], axis = 1) 

AND

df = df.copy() 
df.drop(['SG '], axis = 1)

SG is the column on my data frame that I'm trying to drop.

KeyError: "['SG'] not found in axis"

This is what my data looks like, see on attached image

Image:

3
  • 3
    You might have a (or more) whitespace character in your column name of your dataframe. Tell us the exact output of df.columns. Otherwise, you might have multi-index columns. In that case, tell us what df.info() shows. Commented Aug 27, 2022 at 8:46
  • @Firelord, I thought when I put the command leaving space before SG and also attempted to put it after SG df = df.copy() df.drop(['SG '], axis = 1) AND df = df.copy() df.drop([' SG'], axis = 1) that would help with white space character, clearly it's not helping. You gave me two things to check, df.columns & df.info(), after trying these, I realized that I only get this error when I run the cell twice. I I click run once, "SG" column gets removed but as soon as I click again, the error comes, I guess at this stage it's just telling me indeed "SG" is not there. Commented Aug 27, 2022 at 10:57
  • 1
    When in doubt, print the repr of the column names so that you can see any invisibles that may be lying in wait. Commented Jul 24, 2024 at 23:50

1 Answer 1

1

df.drop(['SG'], axis=1) doesn't change the dataframe inplace.

instead you need to override the DataFrame by doing this below.

df = df.drop(['SG'], axis=1) 

Or by including the argument inplace=True Like this:

df.drop(['SG'], axis=1, inplace=True)

Either option should work fine. I'd recommend using the first option it will be more error prone for the future.

Sign up to request clarification or add additional context in comments.

7 Comments

The problem doesn't seem to be this. OP reported this error. KeyError: "['SG'] not found in axis". Whether you do drop inplace or not should not report this error unless the column doesn't really exist.
How do you construct your dataframe?
I'm not OP. That question should be addressed to OP. :)
ahh alright then.
I assume the DataFrame is probably incorrect in some way or the axis is just 0 and not 1. I tried it myself works just fine.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.