Home > Enterprise >  Python Pandas drop a specific raneg of columns that are all NaN
Python Pandas drop a specific raneg of columns that are all NaN

Time:02-24

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?

CodePudding user response:

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

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

CodePudding user response:

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)

  • Related