1

How do you get indexing [::-1] to reverse ALL 2D array rows and ALL 3D and 4D array columns and rows simultaneously? I can only get indexing [::-1] to reverse 2D array columns. Python

import numpy as np

randomArray = np.round(10*np.random.rand(5,4))
sortedArray = np.sort(randomArray,axis=1)
reversedArray = sortedArray[::-1]
# reversedArray = np.flip(sortedArray,axis=1)

print('Random Array:')
print(randomArray,'\n')
print('Sorted Array:')
print(sortedArray,'\n')
print('Reversed Array:')
print(reversedArray)
Jeremy
  • 113
  • 2
  • 14

1 Answers1

2

You can reverse a dimensions of a numpy array depending on where you place the ::-1.

Lets take a 3D array. For reversing the first dimension:

reversedArray = sortedArray[::-1,:,:]

For reversing the second dimension:

reversedArray = sortedArray[:,::-1,:]

For reversing the third dimension:

reversedArray = sortedArray[:,:,::-1]
joostblack
  • 2,465
  • 5
  • 14
  • At joostblack...[:,::-1,:] is the only index that worked to reverse 3D array columns, and it reversed all of the columns simultaneously. [:,:,::-1] is the only index that worked to reverse 3D array rows, and it reversed all of the rows simultaneously. [:,::-1] worked to reverse 2D array rows, and it reversed all of the rows simultaneously. [:,:,::-1,:] worked to reverse 4D array columns, and it reversed all of the columns simultaneously. [:,:,:,::-1] worked to reverse 4D array rows, and it reversed all of the rows simultaneously. All indexes worked like I wanted. Thanks! – Jeremy Feb 22 '21 at 10:15
  • glad I could help – joostblack Feb 22 '21 at 10:19
  • Yes, I was able to figure out the index to reverse all 4D array columns simultaneously and 4D array rows simultaneously from the indexes you provided. And I forgot that I already had from another source the index to reverse all 2D array rows simultaneously before I posted this thread, but I put the answer in here anyway in case someone else needs it. Again, thanks! – Jeremy Feb 22 '21 at 10:42