Reordering row entries in a numpy array

I am trying to convert a numpy A array to B without using a loop.

A=np.array([[1,2,3],
            [1,3,0],
            [2,0,0]])

B=np.array([[1,2,3],
            [1,0,3],
            [0,2,0]])

Therefore, in each row, I want to change the order of the records, using their value as an index. (i.e., in line 2,, [1,3,0]1 is the first entry, 3 is the third entry, and 0 will be populated as the second entry to make it [1,0,3].

I can do this on a single line so that I can iterate over the array, but I wanted to see if there is a way to do this without a loop. I know that a loop will not matter for small arrays like this, but I'm afraid the loop will create a bottleneck when doing this on large arrays (1 m, 1 m).

Thank!

+4
source share
2

, +1.

In [28]:

import numpy as np
A=np.array([[1,2,3],
            [1,3,0],
            [2,0,0]])
In [29]:

B=np.zeros(A.shape, 'int64')+np.arange(1, A.shape[0]+1)
In [30]:

np.where(np.asarray(map(np.in1d, B, A)), B, 0)
Out[30]:
array([[1, 2, 3],
       [1, 0, 3],
       [0, 2, 0]])
In [31]:

%timeit np.where(np.asarray(map(np.in1d, B, A)), B, 0)
10000 loops, best of 3: 156 µs per loop
+1

, . , :

>>> mask = A != 0
>>> rows, cols = A.shape
>>> idx = (A - 1 + (np.arange(rows)*cols)[:, None])[mask]
>>> B = np.zeros_like(A)
>>> B.ravel()[idx] = A[mask]
>>> B
array([[1, 2, 3],
       [1, 0, 3],
       [0, 2, 0]])

A , A B.

+1

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


All Articles