Reputation: 7022
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?
Upvotes: 6
Views: 4381
Reputation: 587
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)
Upvotes: 13