drop columns with all values having nans in python

To drop columns with all values having NaNs, we can use DataFrame.dropna() method along with the axis parameter set to 1 (since we want to drop columns). We set the how parameter to 'all', which specifies that we only want to drop columns where all values are NaN.

Here's an example:

main.py
import pandas as pd

# create sample dataframe
df = pd.DataFrame({'A': [1, 2, 3, 4],
                   'B': [pd.NA, pd.NA, pd.NA, pd.NA],
                   'C': [2, 4, 6, 8]})

# drop columns with all NaNs
df.dropna(axis=1, how='all', inplace=True)

# print resulting dataframe
print(df)
290 chars
13 lines

This will output:

main.py
   A  C
0  1  2
1  2  4
2  3  6
3  4  8
40 chars
6 lines

As we can see, column B was dropped since all its values were NaN.

related categories

gistlibby LogSnag