【发布时间】:2020-07-09 15:23:14
【问题描述】:
我正在编写代码,一个问题突然出现在我的脑海中。所以基本上我有一个形状为(2, 5, 5) 的 3D numpy 数组和一个形状为 (2, 4) 的 2D numpy 数组(这只是一个示例,数组可以更大)。我需要的是用我的 2D 数组中的值替换 3D 数组(切片 [:, 2:, 2:] )子数组中 1 的值。我想过从 3D 数组中我想要更改的值(那些)中获取索引,然后在 2D 数组中使用 for 循环来迭代这些值,但我不确定它是否是有效的方法,而且我我得到一个错误。
import numpy as np
arr = np.array([[[0., 1., 43., 25., 21.],
[0., 0., 0., 0., 0.],
[0., 43., 0., 1., 0.],
[0., 43., 1., 0., 1.],
[0., 45., 0., 1., 0.]],
[[0., 1., 38., 29., 46.],
[0., 0., 0., 0., 0.],
[0., 32., 0., 0., 1.],
[0., 26., 0., 0., 1.],
[0., 30., 1., 1., 0.]]])
values = [[2, 3, 1, 4],
[4, 1, 5, 9]]
indexes = np.argwhere(newarr[:, 2:, 2:] == 1) + [0, 2, 2]
# indexes = [[0 2 3]
# [0 3 2]
# [0 3 4]
# [0 4 3]
# [1 2 4]
# [1 3 4]
# [1 4 2]
# [1 4 3]]
for i in values:
arr[indexes] == i
#Error
#index 2 is out of bounds for axis 0 with size 2
我想要的输出应该是
newarr = [[[0., 1., 43., 25., 21.],
[0., 0., 0., 0., 0.],
[0., 43., 0., 2., 0.],
[0., 43., 3., 0., 1.],
[0., 45., 0., 4., 0.]],
[[0., 1., 38., 29., 46.],
[0., 0., 0., 0., 0.],
[0., 32., 0., 0., 4.],
[0., 26., 0., 0., 1.],
[0., 30., 5., 9., 0.]]])
我认为只使用 numpy 应该更有效率,但我看不到如何做到这一点,所以任何帮助将不胜感激,谢谢!
【问题讨论】:
标签: python arrays numpy multidimensional-array