The increment of the specified indices in the matrix

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

I have two arrays:

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

together they create indexes that need to be increased:

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

I want to get this matrix:

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

The matrix will be small (for example, 5 ร— 5), and the number of indices will be large (somewhere around 10 ^ 3 or 10 ^ 5).

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

+4
source share
2 answers

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

If the matrix is n x m , you can apply bincount() to a * m + b and build the matrix from the result.

To give an example in your question:

 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]]) 

If the shape of the array is more complex, it may be easier to use np.ravel_multi_index() instead of manually calculating flat indexes:

 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]]) 

(tooltip for @Jaime hat to indicate ravel_multi_index .)

+3
source
 m1 = m.view(numpy.ndarray) # Create view m1.shape = -1 # Make one-dimensional array m1 += np.bincount(a+m.shape[1]*b, minlength=m1.size) 
+2
source

Source: https://habr.com/ru/post/976604/


All Articles