22

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

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?

Évariste Galois
  • 1,043
  • 2
  • 13
  • 27
  • 3
    dropna is not deprecated, only passing axis=1 is. And the deprication message ("Pass tuple or list to drop on multiple axes.") made no sense to me. Any idea what they are talking about? – Qusai Alothman Aug 10 '18 at 23:01
  • Where did you see that `dropna` is duplicated? – rafaelc Aug 10 '18 at 23:06
  • @RafaelC https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html I assumed it wasn't working because of this, but axis=1 didn't work either. – Évariste Galois Aug 10 '18 at 23:33

2 Answers2

52

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

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 here that they made this decision - "let's deprecate passing multiple axes, we don't do this for any other pandas functions".

Jen
  • 635
  • 5
  • 9
5

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

Here's an example

non_null_columns = [col for col in df.columns if df.loc[:, col].notna().any()]
df[non_null_columns]
Henry Woody
  • 14,024
  • 7
  • 39
  • 56