Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 585
Joylove Avatar asked Sep 29 '18 12:09

Joylove


People also ask

How do you drop the column which has no name in pandas?

Method 1: Use the index = False argument But you should also include index = False argument. It will automatically drop the unnamed column in pandas.


2 Answers

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.

like image 68
ipramusinto Avatar answered Oct 23 '22 09:10

ipramusinto


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
like image 34
jpp Avatar answered Oct 23 '22 10:10

jpp