Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: remove leading and trailing zero values from series

Tags:

python

pandas

I would like to remove leading and trailing zeros from a pandas series, i.e. input like

my_series = pandas.Series([0,0,1,2,0,3,4,0,0])

should yield

pandas.Series([1,2,0,3,4])

as output.

I could do this recursively by removing the first (and last) zero and then calling the method again. Is there a more pythonic way of doing this?

like image 677
Anne Avatar asked Dec 19 '22 17:12

Anne


1 Answers

You can use numpys trim_zeros function.

import pandas
import numpy
my_series = pandas.Series([0,0,1,2,0,3,4,0,0])
numpy.trim_zeros(my_series)
like image 86
MonteCarlo Avatar answered Jan 06 '23 09:01

MonteCarlo