1

I have tried to find a similar question but so far it seems only half my question can be answered.

I have a 2D numpy array, e.g.:

a= np.array([[6, 4, 5],
             [4, 7, 8],
             [2, 8, 9]])

And i also have 2 further numpy arrays, indicating the rows, and columns where i would like to rearrange (or not):

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

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

now i would like to rearrange the array "a" based on these indices, so that the result is:

result= np.array([[6, 4, 5],
                  [4, 6, 8],
                  [2, 8, 9]])

Doing this only for columns or only for rows is easy, e.g. see this Thread:

np.array(list(map(lambda x, y: y[x], cols, a)))
shmulik90
  • 63
  • 1
  • 6

1 Answers1

2

This is a typical case of fancy/array indexing:

result = a[rows, cols]

Output:

array([[6, 4, 5],
       [4, 6, 8],
       [2, 8, 9]])
mozway
  • 194,879
  • 13
  • 39
  • 75