英文:
How to expand value of 3d numpy array?
问题
这里是您要的代码部分的中文翻译:
# 假设我有一个3D数组(`3x3x1`),如下所示:
array = [[[149]
[121]
[189]]
[[ 32]
[225]
[ 44]]
[[ 33]
[133]
[ 11]]]
# 如何扩展所有值,使它们在最深层(`3x3x3`)相同,如下所示:
expanded_array = [[[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)
但是它给出了错误信息:
无法将输入数组从形状 (3,) 广播到形状 (1,)
为了通用性,您要如何在 m x n x p
形状格式下实现这一目标?
英文:
Let say I have 3d array (3x3x1
) like this:
[[[149]
[121]
[189]]
[[ 32]
[225]
[ 44]]
[[ 33]
[133]
[ 11]]]
How can I expand all values so they can be the same in the deepest one (3x3x3
) like this:
[[[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]]]
I have tried this:
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)
But it gives me an error:
could not broadcast input array from shape (3,) into shape (1,)
For generalization purposes, how do I achieve this with m x n x p
shape format?
答案1
得分: 4
有多种选项。例如: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)
# 或者
out = np.broadcast_to(arr, (3, 3, 3))
# 或者
out = np.tile(arr, (1, 1, 3))
选择最适合您的方法。
还要注意,具有形状(3, 3, 1)
的数组可能会在不手动重复的情况下自动作为形状(3, 3, 3)
的数组起作用,这是由于广播的原因。
英文:
There are various options. For instance: 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))
choose whichever works most cleanly for you.
Also note that your array with shape (3, 3, 1)
might function as an array with shape (3, 3, 3)
automagically without manually repeating due to broadcasting.
答案2
得分: 1
import numpy as np
arr = np.array([
[[149], [121], [189]],
[[ 32], [225], [ 44]],
[[ 33], [133], [ 11]]
])
print(np.c_[arr, arr, arr])
英文:
There is also np.c_[] way to do it:
import numpy as np
arr = np.array([
[[149], [121], [189]],
[[ 32], [225], [ 44]],
[[ 33], [133], [ 11]]
])
print(np.c_[arr, arr, arr])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论