简体   繁体   中英

Efficiently reshape/reorder numpy array from (a, b, c) to (a, c, b)

I have several Numpy 3D arrays of the shape ( a , b , c ). The values of a , b , and c are unknown. However, I want to reshape each of the arrays to ( a , c , b ) in an efficient way.

Here is what I am doing:

for array in list_of_arrays:
    a, b, c = array.shape
    array = array.reshape(a, c, b)

Is there a more efficient way to do this, possibly in one line of code? Can I use the -1 indexing method to reshape/reorder the arrays?

Thank you.

import numpy as np

# Example array with shape (2, 4, 6)    
array = np.arange(48).reshape((2, 4, 6))

# Swap axis in the 1st and 2nd dimension and print out its shape     
np.swapaxis(array, 1, 2).shape

Output:

(2, 6, 4)

Maybe np.transpose ? It swaps all dimensions to the specified order.

x = np.random.randint(0, 256, (100, 80, 3))

np.transpose(x, (1, 0, 2))
(80, 100, 3)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM