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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.