在 Pandas 0.23+ 中删除空列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51794744/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:55:29  来源:igfitidea点击:

dropping empty columns in pandas 0.23+

pythonpandas

提问by évariste Galois

In earlier versions of pandas, you could drop empty columns simply with:

在早期版本的 Pandas 中,您可以简单地删除空列:

df.dropna(axis='columns')

However, dropna has been depreciated in later builds. How would one now drop multiple (without specifically indexing) empty columns from a dataframe?

但是,dropna 在以后的版本中已经贬值了。现在如何从数据框中删除多个(没有专门索引)空列?

回答by Jen

I am able to drop empty columns using dropna()with the current version of Pandas (0.23.4). The code I used is:

我可以使用dropna()当前版本的 Pandas (0.23.4)删除空列。我使用的代码是:

df.dropna(how='all', axis=1)

Looks like what is deprecated is passing multiple axes at once (i.e. df.dropna(how='all', axis = [0, 1]). You can read herethat they made this decision - "let's deprecate passing multiple axes, we don't do this for any other pandas functions".

看起来不推荐使用的是一次传递多个轴(即df.dropna(how='all', axis = [0, 1])。你可以在这里读到他们做出了这个决定——“让我们弃用传递多个轴,我们不会对任何其他 Pandas 函数这样做”。

回答by Henry Woody

You can get the columns that are not null and then filter your DataFrame on those.

您可以获取不为空的列,然后根据这些列过滤您的 DataFrame。

Here's an example

这是一个例子

non_null_columns = [col for col in df.columns if df.loc[:, col].notna().any()]
df[non_null_columns]