piRSquared piRSquared - 9 days ago 6
Python Question

what is the quickest way to drop zeros from a series

I'm encountered this problem several times and always doing something different each time. What do others do?

Consider the series

s


s = pd.Series([1, 0, 2], list('abc'), name='s')


What is the quickest way to to produce

a 1
c 2
Name: s, dtype: int64

Answer

Boolean slicing is probably the easiest way:

In [1]: s = pd.Series([1, 0, 2], list('abc'), name='s')

In [2]: s[s != 0]
Out[2]:
a    1
c    2
Name: s, dtype: int64