Pandas:如何删除以 nan 作为列名的多列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46101714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas: How to drop multiple columns with nan as col name?
提问by RDJ
As per the title here's a reproducible example:
根据标题,这是一个可重现的示例:
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
Aim is to drop only the columns with nan
as the col name (so keep column y). dropna()
doesn't work as it conditions on the nan
values inthe column, not nan
as the col name.
目的是仅删除nan
列名称为列的列(因此保留列 y)。dropna()
不工作,因为它条件对nan
值在列,而不是nan
作为山坳名。
df.drop(np.nan, axis=1, inplace=True)
works if there's a single column in the data with nan
as the col name. But not with multiple columns with nan
as the col name, as in my data.
df.drop(np.nan, axis=1, inplace=True)
如果数据中只有一列nan
作为 col 名称,则有效。但不是nan
像在我的数据中那样使用多列作为 col 名称。
So how to drop multiple columns where the col name is nan
?
那么如何删除 col 名称所在的多个列nan
?
回答by MaxU
In [218]: df = df.loc[:, df.columns.notnull()]
In [219]: df
Out[219]:
x y
0 this NaN
1 that NaN
2 this NaN
3 that NaN
4 this NaN
回答by Vaishali
You can try
你可以试试
df.columns = df.columns.fillna('to_drop')
df.drop('to_drop', axis = 1, inplace = True)