如何计算到 pandas 系列中前一个零的距离? [英] How to count distance to the previous zero in pandas series?
本文介绍了如何计算到 pandas 系列中前一个零的距离?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下熊猫系列(以列表形式表示):
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?
推荐答案
复杂度为O(n)
.减慢速度的是在python中执行for
循环.如果序列中有k
个零,并且与序列的长度相比log k
是可忽略的,则O(n log k)
解决方案将是:
The complexity is O(n)
. What will slow it down is doing a for
loop in python. If there are k
zeros in the series, and log k
is negligibile comparing to the length of series, an O(n log k)
solution would be:
>>> izero = np.r_[-1, (ts == 0).nonzero()[0]] # indices of zeros
>>> idx = np.arange(len(ts))
>>> idx - izero[np.searchsorted(izero - 1, idx) - 1]
array([1, 2, 0, 1, 2, 3, 4, 0, 1, 2])
这篇关于如何计算到 pandas 系列中前一个零的距离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文