python - 一维numpy数组中到下一个非零元素的距离
问题描述
我有一个由 1 和 0 组成的一维 numpy 数组,如下所示:
[0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1]
对于数组的每个非零元素,我想计算到下一个非零元素的“距离”。也就是说,我想回答“下一个非零元素还有多远?”这个问题。所以上述数组的结果是:
[0, 0, 0, 1, 3, 0, 0, 6, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0]
是否有内置的 numpy 函数?如果没有,在 numpy 中实现这一点的最有效方法是什么?
解决方案
咱们试试吧:
import numpy as np
arr = np.array([0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1])
# create output
res = np.zeros_like(arr)
# select indices non-zero
where, = np.where(arr)
# assign the indices of the non-zero the diff
res[where[:-1]] = np.diff(where)
print(res)
输出
[0 0 0 1 3 0 0 6 0 0 0 0 0 4 0 0 0 0]
推荐阅读
- reactjs - 我正在调用 Firestore 代码的动作创建者
- java - 如何使用 Java 中的 Firestore 中的数据创建饼图
- javascript - 如何将一个脚本的输出传递到 javascript 中的弹出 url?
- python - 将本地计算机时钟与 NTP 时间同步
- python - 如何强制 python matplotlib 到轴进行线性缩放?
- javascript - 我想将一些代码从代码笔切换到 Visual Studio 代码
- networking - 计算与链接节点的交互 [netlogo]
- java - 如何判断一个反应是否被使用 JDA 的不和谐机器人删除?
- image-processing - 未考虑 Thumbor focus() 过滤器
- mysql - Mysql 计算 Sum(if()) 中的不同 ID