[英]Select entry that satisfies condition
我正在使用numPy并具有以下结构:
self.P = np.zeros((self.nS, self.nA, self.nS))
例如,这种结构的一个实例是:
Pl = np.zeros((7,2,7))
Pl[0,0,1]=1
Pl[1,0,2]=1
Pl[2,0,3]=1
Pl[3,0,4]=1
Pl[4,0,5]=1
Pl[5,0,6]=0.9
Pl[5,0,5]=0.1
Pl[6,0,6]=1
Pl[0,1,0]=1
Pl[1,1,1]=0
Pl[1,1,0]=1
Pl[2,1,1]=1
Pl[3,1,2]=1
Pl[4,1,3]=1
Pl[5,1,4]=1
Pl[6,1,5]=1
现在,我要做的就是给定数字e,选择一个分配的值<e的条目。
另一个条件是我知道第一个条目(在示例中为nS或x),但其他两个条目可能会有所不同。
我尝试以这种方式实现它:
self.P[self.P[x,:,:] < e]
但这给了我这个错误:
IndexError: boolean index did not match indexed array along dimension 0; dimension is 7 but corresponding boolean dimension is 2
任何帮助都非常感谢。
当前尝试的问题是您使用布尔掩码对整个数组进行索引,该布尔掩码仅是所选切片的大小,这将导致IndexError
。
亲自检查形状:
>>> Pl.shape
(7, 2, 7)
>>> x = 2
>>> (Pl[x] < 5).shape
(2, 7)
>>> Pl[Pl[x] < 5]
IndexError: boolean index did not match indexed array along dimension 0; dimension is 7
but corresponding boolean dimension is 2
相反,您只想将布尔蒙版应用于所选的维度:
print(Pl[x])
array([[0., 0., 0., 1., 0., 0., 0.],
[0., 1., 0., 0., 0., 0., 0.]])
e = 0.5
Pl[x, Pl[x] < e]
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.