【问题标题】:Numpy: How to quickly replace equal values in an matrix?Numpy:如何快速替换矩阵中的相等值?
【发布时间】:2019-10-19 17:16:08
【问题描述】:

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

一种天真的方法将涉及使用布尔索引,这将导致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!

(请注意,稍后我将需要这些索引进行写访问,即替换存储在数组中的值。但在这些操作之间,我确实需要二维结构。)

【问题讨论】:

  • 也许numpy.argwhere ?类似[np.argwhere(a == x) for x in np.unique(a)] ..?
  • 最终输出会是什么样子?考虑到元素的数量可能是可变的,这可能会使寻找删除循环时的事情变得复杂。
  • @ChrisA 谢谢,这与我正在寻找的内容很接近,至少它简化了代码。这样做的问题是您仍然需要 O(n*m) 操作,因为您将每个值 x 与整个输入数组进行比较。
  • @Divakar 理想情况下是索引列表的集合,其中每个列表对应一个值。 (就像我的例子中的index_i, index_j。)
  • 温馨提示 - 对发布的解决方案有任何反馈吗?

标签: python arrays numpy indexing


【解决方案1】:

这是一个基于 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:]))}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    相关资源
    最近更新 更多