我面临以下问题。我有一个 np.array
,其结构如下:
[A, B, C, D, E, F]
其中 A..F
是 numpy 数组,保证大小相同。
我希望能达到以下形状:
[ A | B, C | D, E | F ]
其中 A | B
是 np.hstack([A, B])
。我还希望能够将其概括为 hstack
中的任意数量的元素,前提是该数字除以该数组的长度。
我不确定如何实现这一目标 - 可能有一些不错的解决方案,但我的经验并没有引导我实现这一目标。我希望能得到一些见解。
最佳答案
用较小的 block 组成 NumPy 数组的手动方法是使用 np.block
或np.bmat
:
h, w, N = 3, 4, 6
A, B, C, D, E, F = [np.full((h,w), i) for i in list('ABCDEF')]
result = np.block([[A, B], [C, D], [E, F]])
产量
array([['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
['C', 'C', 'C', 'C', 'D', 'D', 'D', 'D'],
['C', 'C', 'C', 'C', 'D', 'D', 'D', 'D'],
['C', 'C', 'C', 'C', 'D', 'D', 'D', 'D'],
['E', 'E', 'E', 'E', 'F', 'F', 'F', 'F'],
['E', 'E', 'E', 'E', 'F', 'F', 'F', 'F'],
['E', 'E', 'E', 'E', 'F', 'F', 'F', 'F']],
dtype='<U1')
<小时/>
假设 block 是 2D 数组, reshape NumPy block 数组的更自动化方法是使用 unblockshaped
:
import numpy as np
def unblockshaped(arr, h, w):
"""
http://stackoverflow.com/a/16873755/190597 (unutbu)
Return an array of shape (h, w) where
h * w = arr.size
If arr is of shape (n, nrows, ncols), n sublocks of shape (nrows, ncols),
then the returned array preserves the "physical" layout of the sublocks.
"""
n, nrows, ncols = arr.shape
return (arr.reshape(h // nrows, -1, nrows, ncols)
.swapaxes(1, 2)
.reshape(h, w))
h, w, N = 3, 4, 6
arr = np.array([np.full((h,w), i) for i in list('ABCDEF')])
result = unblockshaped(arr, h*N//2, w*2)
print(result)
产生相同的结果。
<小时/>参见this question举个例子 如何将图像序列排列到网格中。
关于python - 如何将 numpy 数组的元素按二分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46181432/