Numpy:如何快速替换矩阵中的相等值?

2024-06-25 23:22:39 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我们有一个秩2数组a,其中n项在{0,1,2,...,m}中包含整数值。现在,对于这些整数中的每一个,我想找到具有这个值的a项的索引(在下面的示例中称为index_i, index_j)。(所以我要找的是np.unique(...,return_index=True)但是对于2d数组,并且可以返回每个唯一值的所有索引。)

一个简单的方法是使用布尔索引,这将导致O(m*n)操作(见下文),但我只希望有O(n)操作。虽然我找到了一个解决方案,但我觉得应该有一个内置的方法,或者至少可以简化这个过程,或者至少可以消除这些丑陋的循环:

import numpy as np
a = np.array([[0,0,1],[0,2,1],[2,2,1]])
m = a.max()


#"naive" in O(n*m)
i,j = np.mgrid[range(a.shape[0]), range(a.shape[1])]
index_i = [[] for _ in range(m+1)]
index_j = [[] for _ in range(m+1)]
for k in range(m+1):
  index_i[k] = i[a==k]
  index_j[k] = j[a==k]

#all the zeros:
print(a[index_i[0], index_j[0]])
#all the ones:
print(a[index_i[1], index_j[1]])
#all the twos:
print(a[index_i[2], index_j[2]])


#"sophisticated" in O(n)

index_i = [[] for _ in range(m+1)]
index_j = [[] for _ in range(m+1)]
for i in range(a.shape[0]):
  for j in range(a.shape[1]):
    index_i[a[i,j]].append(i)
    index_j[a[i,j]].append(j)

#all the zeros:
print(a[index_i[0], index_j[0]])
#all the ones:
print(a[index_i[1], index_j[1]])
#all the twos:
print(a[index_i[2], index_j[2]])

Try it online!

(请注意,我将在以后的写访问中需要这些索引,即替换存储在数组中的值。但在这些操作之间,我确实需要使用2d结构。)


Tags: the方法inforindexnponeszeros
1条回答
网友
1楼 · 发布于 2024-06-25 23:22:39

这是一个基于sorting的字典,其目的是在迭代以保存为字典时进行最少的工作,其中键是唯一的元素,值是索引-

shp = a.shape
idx = a.ravel().argsort()
idx_sorted = np.c_[np.unravel_index(idx,shp)]
count = np.bincount(a.ravel())
valid_idx = np.flatnonzero(count!=0)
cs = np.r_[0,count[valid_idx].cumsum()]
out = {e:idx_sorted[i:j] for (e,i,j) in zip(valid_idx,cs[:-1],cs[1:])}

样本输入,输出-

In [155]: a
Out[155]: 
array([[0, 2, 6],
       [0, 2, 6],
       [2, 2, 1]])

In [156]: out
Out[156]: 
{0: array([[0, 0],
        [1, 0]]), 1: array([[2, 2]]), 2: array([[0, 1],
        [1, 1],
        [2, 0],
        [2, 1]]), 6: array([[0, 2],
        [1, 2]])}

如果序列中的所有整数都包含在数组中,我们可以将其简化一点-

shp = a.shape
idx = a.ravel().argsort()
idx_sorted = np.c_[np.unravel_index(idx,shp)]
cs = np.r_[0,np.bincount(a.ravel()).cumsum()]
out = {iterID:idx_sorted[i:j] for iterID,(i,j) in enumerate(zip(cs[:-1],cs[1:]))}

相关问题 更多 >