假设我有一个3d数组(3x3x1
)像这样:
[[[149]
[121]
[189]]
[[ 32]
[225]
[ 44]]
[[ 33]
[133]
[ 11]]]
我如何展开所有的值,使它们在最深的一个(3x3x3
)中相同,像这样:
[[[149 149 149]
[121 121 121]
[189 189 189]]
[[ 32 32 32]
[225 225 225]
[ 44 44 44]]
[[ 33 33 33]
[133 133 133]
[ 11 11 11]]]
我已经试过了:
for i in range(len(array)):
for j in range(len(array[i])):
array[i][j] = np.array(list(array[i][j]) * 3)
print(array)
但是它给了我一个错误:
could not broadcast input array from shape (3,) into shape (1,)
为了一般化的目的,我如何用m x n x p
形状格式实现这一点?
有多种选择。例如:np.repeat
,np.tile
,np.broadcast_to
:
import numpy as np
arr = np.array([
[[149], [121], [189]],
[[ 32], [225], [ 44]],
[[ 33], [133], [ 11]]
])
out = np.repeat(arr, 3, axis=2)
# or
out = np.broadcast_to(arr, (3, 3, 3))
# or
out = np.tile(arr, (1, 1, 3))
选择最适合你的。
还请注意,形状为(3, 3, 1)
的数组可以自动地作为形状为(3, 3, 3)
的数组运行,而无需由于广播而手动重复。
也有np.c_[]方法:
import numpy as np
arr = np.array([
[[149], [121], [189]],
[[ 32], [225], [ 44]],
[[ 33], [133], [ 11]]
])
print(np.c_[arr, arr, arr])