选择满足条件的条目

2024-03-28 10:19:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是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

非常感谢您的帮助。你知道吗


Tags: 实例selfnumpyisnpzeros条目数字
1条回答
网友
1楼 · 发布于 2024-03-28 10:19:45

当前尝试的问题是,使用仅为所选切片大小的布尔掩码索引整个数组,从而导致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.])

相关问题 更多 >