Rearrange rows of a given numpy 2D array given a list with the permutations

Viewed 100

There's an incredibly simple way of permuting the columns of a 2d array with numpy like this:

array1 = np.array([[11, 22, 33, 44, 55],
                  [66,  77,  88,  99, 100]])

print("Original array:")
print(array1)
permutation = [1,3,0,4,2]

result = array1[:, permutation]
print("New array:")
print(result)

This outputs:

Original array:
[[ 11  22  33  44  55]
 [ 66  77  88  99 100]]
New array:
[[ 22  44  11  55  33]
 [ 77  99  66 100  88]]

Visual representation (from w3resource.com)

Is there a way to acomplish the same thing as elegantly but for the rows instead?

1 Answers

As @Marat mentioned in the comments, you can do the same by similar advanced indexing that you described for columns:

array1 = np.array([[11, 22, 33, 44, 55],
                  [66,  77,  88,  99, 100]])
permutation = [1,0]
array1[permutation]
#[[ 66  77  88  99 100]
# [ 11  22  33  44  55]]

When you advance index numpy array, the default is calling rows.

Related