简体   繁体   中英

Aligning N-dimensional numpy arrays

I am putting data in numpy arrays for comparisons. They way the data is stored sometimes the dimensions are out of order. For example if the first array has the shape (10, 20, 30, 40), sometimes the second array will have the shape (10, 20, 40, 30). We can assume that the lengths of the dimensions will be unique.

Is there an easy way to convert the shape of the second array to the shape of the first without knowing the number of dimensions or the length of the dimensions beforehand? I think I can do it with a long series of elif statements and transpose operations, but I'm hoping there is a cleaner method available.

Use shape.index to find where each axis needs to be, then use transpose to re-order the axes:

import numpy as np
A = np.ones((10, 20, 40, 30))
B = np.ones((10, 20, 30, 40))

new_order = [A.shape.index(i) for i in B.shape]
B = B.transpose(new_order)

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