我正在尝试执行以下操作:我有一个三维数组X,形状为(Z,M,N)。我有一个shape(M)的单独的一维数组Y,其中包含整数值,其中大于0的值表示X中希望在Y中设置相应值的行。例如,请参见以下情形:
X =
[[[0. 0.]
[0. 0.]]
[[1. 1.]
[1. 1.]]
[[1. 1.]
[1. 1.]]
[[1. 1.]
[1. 1.]]
[[1. 1.]
[1. 1.]]]
Y =
[0 1]
应该返回:
[[[0. 0.]
[1. 1.]]
[[1. 1.]
[1. 1.]]
[[1. 1.]
[1. 1.]]
[[1. 1.]
[1. 1.]]
[[1. 1.]
[1. 1.]]]
或何时Y = [0 0]
,应返回:
[[[0. 0.]
[0. 0.]]
[[1. 1.]
[1. 1.]]
[[1. 1.]
[1. 1.]]
[[1. 1.]
[1. 1.]]
[[1. 1.]
[1. 1.]]]
以下代码适用于第一种情况,但在第二种情况下会引发以下错误,这似乎是我无法解决的。我正在Windows 10 Pro上使用Python 3.6.8运行它。
Traceback (most recent call last):
File "blah2.py", line 41, in <module>
r[np.where(y>0), :] = y[np.where(y>0)]
ValueError: shape mismatch: value array of shape (0,) could not be broadcast to indexing result of shape (1,0,2)
import numpy as np
x = np.ones((5, 2, 2))
y = np.array([0, 0])
r = np.zeros((2,2))
r[np.where(y>0), :] = y[np.where(y>0)]
x[0] = r
print(x)
您需要将索引扩展y
到2D
,然后再分配,以便它可以针对索引进行广播x
-
x[0,np.where(y>0),:] = y[np.where(y>0),None]
或更好的方法是mask
在将索引扩展y
到2D
-时简单地使用a和Assign
m = y>0 # get mask of comparisons
x[0,m,:] = y[m,None]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句