我将数据存储在三个不同的数组中:A、B 和 C。
我还有一个整数数组 Z,其中包含 1、2 或 3。
A、B、C、Z的形状相同。
我想创建一个新数组 D,如果 Z 中的相应元素为 1,则包含 A 中列出的值,如果 Z 中的相应元素为 2,则包含 B 中列出的值,如果 Z 中的相应元素,则包含 C 中列出的值Z 为 3。
为此,我使用嵌套版本的 numpy.where 编写了代码。然而代码看起来很难看。有没有更好的方法来做同样的事情?
import numpy as np
#Create arrays that hold the data
A = np.array([1.,1.,1.])
B = A * 2
C = A * 3
#Create an array that hold the zone numbers
Z = np.array([1,2,3])
#Now calculate the new array by figuring out the appropriate zone at each location
D = np.where(Z==1,A,np.where(Z==2,B, np.where(Z==3,C,0.0)))
#Output
print A
print B
print C
print D
[ 1. 1. 1.]
[ 2. 2. 2.]
[ 3. 3. 3.]
[ 1. 2. 3.]
请您参考如下方法:
看看这是否有效:
new=np.zeros_like(A)
new[Z==1] = A[Z == 1]
new[Z==2] = B[Z == 2]
new[Z==3] = C[Z == 3]
