python - 如何计算到 Pandas 系列中前一个零的距离?

标签 python numpy pandas series

我有以下 pandas 系列(表示为列表):

[7,2,0,3,4,2,5,0,3,4]

我想定义一个新系列,将距离返回到最后一个零。这意味着我想要以下输出:

[1,2,0,1,2,3,4,0,1,2]

如何以最有效的方式在 pandas 中做到这一点?

最佳答案

复杂度为O(n)。什么会减慢它在 python 中执行 for 循环。如果序列中有 k 个零,并且 log k 与序列的长度相比可以忽略不计,O(n log k) 解决方案会是:

>>> 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])

关于python - 如何计算到 Pandas 系列中前一个零的距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30730981/

相关文章:

Python:如何在一个数据框中替换另一个数据框中的列值而不删除重复项

python - 导入错误 : No module named clr when using CPython of python. 组织

python - 如何将 numpy 数组提升为幂? (对应于重复的矩阵乘法,不是逐元素的)

python - 如何用 cython(或 numpy)加速 Pandas

python - 关于在我的代码中更快地执行 for/if 语句的建议?

python - 是否可以从 __init__.py 扩展一个类

python - Spark 作业在 rdd takeSample 上无限期挂起

python - 方法不允许(POST)Django 405 错误

python - 反向外键查找

python - 将数据帧转换为字典,忽略某些值