how to drop columns where only all values are nans in python

You can use the dropna function along with the axis=1, how='all' and inplace=True parameters to drop columns where all the values are nan. Here's an example:

main.py
import pandas as pd

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

# drop columns where all values are nan
df.dropna(axis=1, how='all', inplace=True)

print(df)
237 chars
10 lines

This will output the following dataframe with only the non-nan columns:

main.py
     A    C
 0  1.0  3.0
 1  2.0  4.0
 2  NaN  NaN
51 chars
5 lines

related categories

gistlibby LogSnag