remove only the first entries if they are zeros

Viewed 65

I have a pandas series that looks like this:

df['column_3'].head(10)

0    0.0
1    0.0
2    0.0
3    0.0
4    0.0
5    0.1
6    0.0
7    0.1
8    0.1
9    0.0

I would like to remove only the first appearances of zeros, so in this example only rows 0 - 4. The number of zeros in the beginning of the series may vary and I only want to remove the zeros that come before the first instance of a non-zero entry. When I did this:

df[df['column_3'] != 0.0]

It removes all zeros, no matter the placement, which is not what I want.

I want it to look like this:

5    0.1
6    0.0
7    0.1
8    0.1
9    0.0

Any suggestions?

Thanks!

3 Answers

cumsum is suitable for this situation:

df[df['column_3'].ne(0).cumsum().gt(0)]

Output:

   column_3        
5       0.1
6       0.0
7       0.1
8       0.1
9       0.0

This should help:

df[(df['column_3'].eq(0).cumprod().eq(0))]  

Another way to do this is to find the first row which is not zero and filter only on the rows that are after this row.

first_non_zero = df.column_3.to_numpy().nonzero()[0][0]
df.loc[first_non_zero:,]

Output is

   column_3        
5       0.1
6       0.0
7       0.1
8       0.1
9       0.0
Related