从 2D 列表访问索引 - Python

Access indices from 2D list - Python

我正在尝试访问二维列表中的索引列表,但出现以下错误。基本上我想找到我的数据在两个值之间的位置,并将 'weights' 数组设置为 1.0 以用于以后的计算。

#data = numpy array of size (141,141)
weights = np.zeros([141,141])
ind = [x for x,y in enumerate(data) if y>40. and y<50.]
weights[ind] = 1.0

ValueError: 具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()

我试过使用 np.extract() 但是没有给出索引...

认为我可以做到这一点:

#data = numpy array of size (141,141)
weights = np.zeros([141,141])
ind = ((data > 40.) & (data < 50.)).astype(float) 
weights[np.where(ind==1)]=1.0

感谢有关使用 numpy 的矢量化功能的有用评论。第三行输出一个大小为(141,141)的数组,满足条件的为1,不满足的为0。然后我在这些位置用 1.0 填充了 'weights' 数组。

如果需要用( (value - 40) / 10)填充weights,那么使用numpy.ma更好:

data = np.random.uniform(0, 100, size=(141, 141))
weights = ((np.ma.masked_outside(data, 40, 50) - 40) / 10).filled(0)