选择满足条件的条目

时间:2018-12-05 22:20:12

标签: python arrays numpy matrix

我正在使用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,选择一个条目,其中分配的值是

另一个条件是我知道第一个条目(在示例中为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

我们非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

当前尝试的问题是,您使用布尔型掩码对 entire 数组进行索引,该布尔型掩码仅是所选切片的大小,从而导致IndexError。 / p>

亲自检查形状:

>>> 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.])