0

I'm attempting to drop a range of columns in a pandas dataframe that have all NaN. I know the following code:

df.dropna(axis=1, how='all', inplace = True)

Will search all the columns in the dataframe and drop the ones that have all NaN.

However, when I extend this code to a specific range of columns:

df[df.columns[48:179]].dropna(axis=1, how='all', inplace = True)

The result is the original dataframe with no columns removed. I also no for a fact that the selected range has multiple columns with all NaN's

Any idea what I might be doing wrong here?

2 Answers 2

1

Don't use inplace=True. Instead do this:

cols = df.columns[48:179]
df[cols] = df[cols].dropna(axis=1, how='all')
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, however, that only returns a dataframe containing the variables in the range. How would I return the above columns into the original dataframe?
@r_user Please check my updated answer.
Hmm. I appreciate the help. However, I get a Columns must be same length as key valueerror
0

inplace=True can only used when you apply changes to the whole dataframe. I won't work in range of columns. Try to use dropna without inplace=True to see the results(in a jupyter notebook)

1 Comment

Hi @Anas. You can improve the readability of your answer using the text forma options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.