首页 > 解决方案 > 使不同形状和维度的数组在形状和维度上相等

问题描述

我有 2 个不同的形状和维度数组,并且想通过在这些地方填充 1 来更新它们,以便获得一致的形状和维度。

我可以通过使用循环来做到这一点,我正在寻找没有循环的答案。

A = np.arange(4).reshape(-1,1)
B = np.arange(27).reshape(3,3,3)

A.shape  => (4, 1)
B.shape  => (3, 3, 3)

# Now A.shape should be (4, 3, 3) and B.shape should be (4, 3, 3)

现在我需要帮助来编写一个函数,该函数接受 2 个数组并通过在位置填充 1 来返回 2 个相同维度和形状的数组。

先感谢您。

标签: pythonnumpy

解决方案


我确信有一种更精致的方法,但一种可能的解决方案是:

In [1]: import numpy as np

In [2]: A = np.arange(4).reshape(-1, 1)

In [3]: B = np.arange(27).reshape(3, 3, 3)

In [4]: def resize_to_bigger(A: np.ndarray, B: np.ndarray) -> np.ndarray:
   ...:     taller, smaller = (A, B) if A.size >= B.size else (B, A)
   ...:     # if both sizes are equal reshape to first passed array
   ...:     if taller.size == smaller.size:
   ...:         return smaller.copy().reshape(taller)
   ...:     else:
   ...:         C = np.ones(taller.size)
   ...:         C[:smaller.size] = smaller.flatten()
   ...:         return C.reshape(taller.shape)
   ...:

In [5]: resize_to_bigger(A, B)
Out[5]:
array([[[0., 1., 2.],
        [3., 1., 1.],
        [1., 1., 1.]],

       [[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]],

       [[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]]])

请注意,根本没有检查dtypes 。


推荐阅读