矩阵中给定索引的增量 [英] Increment given indices in a matrix

查看:53
本文介绍了矩阵中给定索引的增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之:有一个类似的问题,最佳答案建议使用numpy.bincount.我需要同样的东西,但是需要一个矩阵.

Briefly: there is a similar question and the best answer suggests using numpy.bincount. I need the same thing, but for a matrix.

我有两个数组:

array([1, 2, 1, 1, 2])
array([2, 1, 1, 1, 1])

它们共同构成了应该递增的索引:

together they make indices that should be incremented:

>>> np.array([a, b]).T
array([[1, 2],
       [2, 1],
       [1, 1],
       [1, 1],
       [2, 1]])

我想得到这个矩阵:

array([[0, 0, 0],
       [0, 2, 1],  # (1,1) twice, (1,2) once
       [0, 2, 0]]) # (2,1) twice

矩阵会很小(例如5×5),索引的数量会很大(在10 ^ 3或10 ^ 5附近).

The matrix will be small (like, 5×5), and the number of indices will be large (somewhere near 10^3 or 10^5).

那么,有什么比for循环更好(更快)的地方吗?

So, is there anything better (faster) than a for-loop?

推荐答案

您仍然可以使用 bincount() .诀窍是将ab转换为平面索引的单个一维数组.

You can still use bincount(). The trick is to convert a and b into a single 1D array of flat indices.

如果矩阵是n x m,则可以将bincount()应用于a * m + b,然后根据结果构造矩阵.

If the matrix is nxm, you could apply bincount() to a * m + b, and construct the matrix from the result.

以问题中的示例为例:

In [15]: a = np.array([1, 2, 1, 1, 2])

In [16]: b = np.array([2, 1, 1, 1, 1])

In [17]: cnt = np.bincount(a * 3 + b)

In [18]: cnt.resize((3, 3))

In [19]: cnt
Out[19]: 
array([[0, 0, 0],
       [0, 2, 1],
       [0, 2, 0]])

如果数组的形状更复杂,则使用 np.ravel_multi_index() 而不是手动计算平面索引:

If the shape of the array is more complicated, it might be easier to use np.ravel_multi_index() instead of computing flat indices by hand:

In [20]: cnt = np.bincount(np.ravel_multi_index(np.vstack((a, b)), (3, 3)))

In [21]: np.resize(cnt, (3, 3))
Out[21]: 
array([[0, 0, 0],
       [0, 2, 1],
       [0, 2, 0]])

(提示@Jaime的提示提示ravel_multi_index.)

(Hat tip @Jaime for pointing out ravel_multi_index.)

这篇关于矩阵中给定索引的增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆