【问题标题】:numpy create 2D mask from list of indices [+ then draw from masked array]numpy 从索引列表创建 2D 掩码 [+ 然后从掩码数组中绘制]
【发布时间】:2014-10-21 12:28:45
【问题描述】:

我有一个二维值数组,需要屏蔽该数组的某些元素(索引取自约 100k 元组对的列表),然后从剩余元素中抽取随机样本而不进行替换。

我需要既快速/高效(希望避免 for 循环)又占用内存小的东西,因为实际上主阵列约为 20000 x 20000。

现在我会满足于(用于说明):

xys=[(1,2),(3,4),(6,9),(7,3)]

gxx,gyy=numpy.mgrid[0:100,0:100]
mask = numpy.where((gxx,gyy) not in set(xys)) # The bit I can't get right

# Now sample the masked array
draws=numpy.random.choice(master_array[mask].flatten(),size=40,replace=False)

幸运的是,现在我不需要绘制通量的 x,y 坐标 - 但如果您知道一种有效的方法来一步完成所有这些操作(即我可以先识别这些坐标是可以接受的)然后使用它们来获取对应的 master_array 值;上图是一个捷径)。

谢谢!

相关问题:

Numpy mask based on if a value is in some other list

Mask numpy array based on index

Implementation of numpy in1d for 2D arrays?

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    您可以使用稀疏 coo 矩阵有效地做到这一点

    from scipy import sparse
    xys=[(1,2),(3,4),(6,9),(7,3)]
    
    coords = zip(*xys)
    mask = sparse.coo_matrix((numpy.ones(len(coords[0])), coords ), shape= master_array.shape, dtype=bool)
    draws=numpy.random.choice( master_array[~mask.toarray()].flatten(), size=10)
    

    【讨论】:

    • 感谢您提供快速而优雅的解决方案!
    • 啊 - 我试图 避免 xys 中的任何对 - 因此第三种解决方案的逻辑反转了吗?第二个可以吗?
    • 嗯,好的,但是你需要将它们全部反转。并且编辑不再有效
    猜你喜欢
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 2022-08-10
    • 2022-10-18
    • 2020-05-02
    • 1970-01-01
    相关资源
    最近更新 更多