Anne
Anne

Reputation: 7022

Pandas: remove leading and trailing zero values from series

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

Answers (1)

MonteCarlo
MonteCarlo

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

Related Questions