根据标题,这是一个可重现的示例:
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
作为 col 名称,则有效,但是不像在我的数据中那样,使用 nan
作为 col 名称的多个列。
那么如何删除列名为 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
关于python - Pandas:如何删除以 nan 作为列名的多列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46101714/