Pandas dataframe drop columns with no header

  • A+
Category:Languages

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.

 


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 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: