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.
Method 1: Use the index = False argument But you should also include index = False argument. It will automatically drop the unnamed column in pandas.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With