【问题标题】:Make arrays of different shape and dimension equal in shape and dimension使不同形状和维度的数组在形状和维度上相等
【发布时间】:2021-03-21 21:31:59
【问题描述】:

我有 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 个相同维度和形状的数组。

提前谢谢你。

【问题讨论】:

  • 展示你如何使用循环来做到这一点。如果您知道如何制作具有正确大小的 ones 数组,并且您知道为数组的切片/块分配值的基础知识,那么无循环版本应该很容易。

标签: python numpy


【解决方案1】:

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

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。

【讨论】:

    猜你喜欢
    • 2021-02-02
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多