user308827 user308827 - 1 year ago 212
Python Question

Drop rows with all zeros in pandas data frame

I can use

pandas
dropna()
functionality to remove rows with some or all columns set as
NA
's. Is there an equivalent function for dropping rows with all columns having value 0?

P kt b tt mky depth
1 0 0 0 0 0
2 0 0 0 0 0
3 0 0 0 0 0
4 0 0 0 0 0
5 1.1 3 4.5 2.3 9.0


In this example, we would like to drop the first 4 rows from the data frame.

thanks!

Answer Source

It turns out this can be nicely expressed in a vectorized fashion:

> df = pd.DataFrame({'a':[0,0,1,1], 'b':[0,1,0,1]})
> df = df[(df.T != 0).any()]
> df
   a  b
1  0  1
2  1  0
3  1  1