python - 如何快速获取numpy数组中非零值的索引?

标签 python algorithm numpy data-structures

现在我正在编写一个函数,它按照以下规则获取非零值的索引:

  1. 预期结果是一个列表。每个元素表示连续的非零值切片的索引。所以对于 [0,0,0,1,1,1,0,1,1,0] 的列表, 它应该得到列表 [[3,4,5], [7,8]]
  2. 列表中不同值的索引应该在单独的列表中,即对于[0,0,1,1,1,2,2,1,1,0]的列表。 , 预期结果为 [[2,3,4],[5,6],[7,8]] .

你有什么想法吗?先感谢您!

最佳答案

arr 作为输入数组并将数组列表作为输出,您可以这样做 -

# Store non-zero element indices
idx = np.where(arr)[0]

# Get indices where the shifts occur, i.e. positions where groups of identical 
# elements are separated. For this we perform differnetiation and look for 
# non-zero values and then get those positions. Finally, add 1 to compensate 
# for differentiation that would have decreased those shift indices by 1.
shift_idx = np.where(np.diff(arr[idx])!=0)[0]+1

# Split the non-zero indices at those shifts for final output
out = np.split(idx,shift_idx)

示例输入、输出-

In [35]: arr
Out[35]: array([0, 0, 1, 1, 1, 2, 2, 1, 1, 0, 2, 2, 4, 3, 3, 3, 0])

In [36]: out
Out[36]: 
[array([2, 3, 4]),
 array([5, 6]),
 array([7, 8]),
 array([10, 11]),
 array([12]),
 array([13, 14, 15])]

关于python - 如何快速获取numpy数组中非零值的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38049793/

相关文章:

python - ldap python result3 函数结果中缺少 LDAP 属性,但出现在 ldapsearch 命令结果中

python - 识别产生 KeyError 的丢失键的位置

algorithm - 处理不断变化的数据的方法

php - 将 Python 或 Perl 与 PHP 集成

java - 数独 - 根据行、列、维度 (?) 和框大小查找当前框(正方形或矩形)

javascript - 为什么在执行递归回调时 .foreach 的行为与 for...of 不同?

python-将col名称添加到np.array

python - 附加一个 numpy 数组,但以二维方式组织附加信息

python - 对非常大的 numpy 数组按 ID 进行分组的最快方法

Python 面向对象编程。编写程序来执行丰富的比较