'Python Pandas drop a specific raneg of columns that are all NaN

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?



Solution 1:[1]

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

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

Solution 2:[2]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Anas