【问题标题】:Access indices from 2D list - Python从二维列表访问索引 - Python
【发布时间】:2016-05-28 02:57:26
【问题描述】:

我正在尝试访问二维列表中的索引列表,但出现以下错误。基本上我想找到我的数据在两个值之间的位置,并将“权重”数组设置为 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() 但这并没有给出索引...

【问题讨论】:

  • 或者使用 NumPy 的矢量化功能:((data &gt; 40) &amp; (data &lt; 50)).astype(float)?

标签: python-2.7 numpy indexing indices


【解决方案1】:

认为我可以做到这一点:

#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.0s 填充我的“权重”数组。

【讨论】:

  • 其实((data &gt; 40) &amp; (data &lt; 50)).astype(float) 应该是你的weights 本身,而不是与ind 混在一起。
  • 我实际上需要对满足这些条件的数据值进行一些数学运算。所以介于 40 和 50 之间的值我会应用一个等式来 ( (value - 40) / 10)
【解决方案2】:

如果您需要用( (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)

【讨论】:

    猜你喜欢
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多