python - 使不同形状和维度的数组在形状和维度上相等
问题描述
我有 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 个相同维度和形状的数组。
先感谢您。
解决方案
我确信有一种更精致的方法,但一种可能的解决方案是:
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.]]])
请注意,根本没有检查dtype
s 。
推荐阅读
- kubernetes - 根据 Drone CI 中的外部变量不同的构建步骤
- python - 由于明显的版本与 tensorflow 冲突,tensorflowjs 的 Pip 安装无法正常工作
- twilio - 在 twilio 动作 json 中指定语音
- c# - 没有连接字符串时`dbcontext.savechanges()`在哪里保存数据
- javascript - 单击背景或按 esc 时,模态不会关闭
- python - 我有每周卫星数据,但我想将其转换为每月数据。我该怎么做?
- amazon-web-services - 从 SFTP 获取文件到 S3 AWS
- python-3.x - 如何使用 mplcursors 在条形图上添加悬停注释
- visual-studio-2015 - 如何使用 SSIS Merge Join - 无法按预期工作
- sql - 展平表中可能为 NULL 或空的数组