Search code examples
pythonnumpymultidimensional-arraymatrix-indexing

Indexing [::-1] to Reverse ALL 2D Array Rows and ALL 3D and 4D Array Columns and Rows Simultaneously Python


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)

Solution

  • 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]