I have the following pandas series (represented as a list):
[7,2,0,3,4,2,5,0,3,4]
I would like to define a new series that returns distance to the last zero. It means that I would like to have the following output:
[1,2,0,1,2,3,4,0,1,2]
How to do it in pandas in the most efficient way?
It's sometimes surprising to see how simple it is to get c-like speeds for this stuff using Cython. Assuming your column's
.values
givesarr
, then:Note the use of typed memory views, which are extremely fast. You can speed it further using
@cython.boundscheck(False)
decorating a function using this.