Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Eliminate first and last rows with value 0 from dataframe

I have a dataframe with a row with integers such as

 value
0
0
0
0
1
2
0
3
0
2
5
6
0
0
0

Is there a way that I can eliminate the first 0s and last 0s (but not the ones in the middle) to get

1
2
0
3
0
2
5
6

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Create mask and filter all non 0 values after first match by Series.cummax and chain reversed order of condition for eliminate last 0 by & for bitwise AND with filter in boolean indexing:

m = df['value'].ne(0)
out = df[m.cummax() & m.iloc[::-1].cummax()]
print (out)
    value
4       1
5       2
6       0
7       3
8       0
9       2
10      5
11      6
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading