Python Forum

Full Version: How to delete column if entire column values are "nan"
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I have read csv file in dataframe, and I want to delete column if entire column values are equal to "nan"


data.csv:

Name    Rank   subname prevname
USA Ca   12     23     nan
USA WD   25     78     nan
RSA      45     nan    nan
not always the entire 3rd row has "nan" values.

I use the below code:
import pandas as pd
df=pd.read_csv(r'data.csv')
 
df.dropna(axis=1, how='all')
There are at least several ways to do what you want:

# 1
df.drop('prevname', axis=1, inplace=True)

# 2
df = df.iloc[:,:-1] # we assume that prevname is a last column

# 3
df = df[['Name', 'Rank', 'subname']]
we do not know which column has nan values beforehand, and column names are not the same always.
(Apr-11-2019, 12:28 PM)Sri Wrote: [ -> ]we do not know which column has nan values beforehand, and column names are not the same always.

In this case, using .dropna is a good choice. You need to pass inplace=True: df.dropna(axis=1, how='all', inplace=True).
Thanks a lot!