Joylove
Joylove

Reputation: 414

Pandas dataframe drop columns with no header

What's the most pythonic place to drop the columns in a dataframe where the header row is NaN? Preferably inplace.

There may or may not be data in the column.

df = pd.DataFrame({'col1': [1,2,np.NaN], 'col2': [4,5,6], np.NaN: [7,np.NaN,9]})
df.dropna(axis='columns', inplace=True)  

Doesn't do it as it looks at the data in the column.

Wanted output

df = pd.DataFrame({'col1': [1,2,np.NaN], 'col2': [4,5,6]})

Thanks in advance for the replies.

Upvotes: 12

Views: 14305

Answers (2)

ipramusinto
ipramusinto

Reputation: 2668

Simply try this

df.drop(np.nan, axis=1, inplace=True)

However, if 'no headers' includes None, then jpp's answer will work perfectly at one shot. Even, in case you have more than one np.nan headers, I don't know how to make df.drop works.

Upvotes: 7

jpp
jpp

Reputation: 164843

You can use pd.Index.dropna:

df = df[df.columns.dropna()]

print(df)

   col1  col2
0   1.0     4
1   2.0     5
2   NaN     6

Upvotes: 5

Related Questions