【发布时间】:2020-04-28 14:00:34
【问题描述】:
这与之前的帖子有关:Numpy random choice of tuples
我有一个 2D numpy 数组,并想使用 2D 概率数组从中进行选择。我能想到的唯一方法是展平,然后使用模数和余数将结果转换回二维索引
import numpy as np
# dummy data
x=np.arange(100).reshape(10,10)
# dummy probability array
p=np.zeros([10,10])
p[4:7,1:4]=1.0/9
xy=np.random.choice(x.flatten(),1,p=p.flatten())
index=[int(xy/10),(xy%10)[0]] # convert back to index
print(index)
这给了
[5, 2]
但是有没有一种更简洁的方法可以避免展平和取模?即我可以将坐标元组列表作为 x 传递,但是我该如何处理权重?
【问题讨论】:
-
我觉得这个方法很好,你可以用unravel_index替换除法/取模