简体   繁体   English

对齐 N 维 numpy 数组

[英]Aligning N-dimensional numpy arrays

I am putting data in numpy arrays for comparisons.我将数据放在 numpy 数组中进行比较。 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).例如,如果第一个数组的形状为 (10, 20, 30, 40),则有时第二个数组的形状为 (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.我想我可以用一长串 elif 语句和转置操作来完成,但我希望有一种更清晰的方法可用。

Use shape.index to find where each axis needs to be, then use transpose to re-order the axes:使用shape.index找到每个轴需要的位置,然后使用 transpose 重新排序轴:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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