pandas :如何删除以NaN为列名的多个列? [英] Pandas: How to drop multiple columns with nan as col name?
本文介绍了 pandas :如何删除以NaN为列名的多个列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
根据标题,下面是一个可重复使用的示例:
raw_data = {'x': ['this', 'that', 'this', 'that', 'this'],
np.nan: [np.nan, np.nan, np.nan, np.nan, np.nan],
'y': [np.nan, np.nan, np.nan, np.nan, np.nan],
np.nan: [np.nan, np.nan, np.nan, np.nan, np.nan]}
df = pd.DataFrame(raw_data, columns = ['x', np.nan, 'y', np.nan])
df
x NaN y NaN
0 this NaN NaN NaN
1 that NaN NaN NaN
2 this NaN NaN NaN
3 that NaN NaN NaN
4 this NaN NaN NaN
目的是只删除列名为nan
的列(因此保留列y
)。dropna()
不适用于列中的nan
值,而不是列名称中的nan
。
df.drop(np.nan, axis=1, inplace=True)
如果数据中只有一列以nan
作为列名,而不是像我的数据中那样有多列以nan
作为列名。
那么如何删除列名称为nan
的多个列?
推荐答案
In [218]: df = df.loc[:, df.columns.notna()]
In [219]: df
Out[219]:
x y
0 this NaN
1 that NaN
2 this NaN
3 that NaN
4 this NaN
这篇关于 pandas :如何删除以NaN为列名的多个列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文