Delete zeros from a pandas dataframe

Viewed 2616

This question was asked in multiple other posts but I could not get any of the methods to work. This is my dataframe:

df = pd.DataFrame([[1,2,3,4.5],[1,2,0,4,5]])

I would like to know how I can either:

1) Delete rows that contain any/all zeros 2) Delete columns that contain any/all zeros

In order to delete rows that contain any zeros, this worked:

df2 = df[~(df == 0).any(axis=1)]
df2 = df[~(df == 0).all(axis=1)]

But I cannot get this to work column wise. I tried to set axis=0 but that gives me this error:

__main__:1: UserWarning: Boolean Series key will be reindexed to match DataFrame index.

Any suggestions?

1 Answers

You're going to need loc for this:

df
   0  1  2  3  4
0  1  2  3  4  5
1  1  2  0  4  5

df.loc[:, ~(df == 0).any(0)]  # notice the :, this means we are indexing on the columns now, not the rows
   0  1  3  4
0  1  2  4  5
1  1  2  4  5

Direct indexing defaults to indexing on the rows. You are trying to index a dataframe with only two rows using [0, 1, 3, 4], so pandas is warning you about that.

Related