Python 带权重的numpy随机选择的2D版本

Python 带权重的numpy随机选择的2D版本,python,numpy,random,Python,Numpy,Random,这与先前的这篇文章有关: 我有一个2D numpy数组,希望使用2D概率数组从中进行选择。我能想到的唯一方法是展平,然后使用模和余数将结果转换回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.flatte

这与先前的这篇文章有关:

我有一个2D numpy数组,希望使用2D概率数组从中进行选择。我能想到的唯一方法是展平,然后使用模和余数将结果转换回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]


但是有没有一种更干净的方法可以避免扁平化和模化呢?i、 e.我可以将坐标元组列表传递为x,但如何处理权重?

我认为不可能直接指定2D形状的概率数组。所以拉弗林应该没问题。但是,要从平面索引中获得相应的二维形状索引,可以使用


对于多个索引,您可以只堆叠结果:

xy=np.random.choice(x.flatten(),3,p=p.flatten())

indices = np.unravel_index(xy, x.shape)
# (array([4, 4, 5], dtype=int64), array([1, 2, 3], dtype=int64))
np.c_[indices]
array([[4, 1],
       [4, 2],
       [5, 3]], dtype=int64)
其中
np.c
,并给出与

np.column_stack(indices)

您可以使用
numpy.random.randint
生成索引,例如:

# assumes p is a square array
ij = np.random.randint(p.shape[0], size=p.ndim) # size p.ndim = 2 generates 2 coords

# need to convert to tuple to index correctly
p[tuple(i for i in ij))]
>>> 0.0
您还可以一次索引多个随机值:

ij = np.random.randint(p.shape[0], size=(p.ndim, 5)) # get 5 values
p[tuple(i for i in ij))]
>>> array([0.        , 0.        , 0.        , 0.11111111, 0.        ])

我认为这个方法很好,你可以用nice代替除法/模,谢谢,randint的唯一问题是我认为它不允许我应用权重,或者我错了吗?不,我认为你是对的
randint
没有概率参数,但是
choice
有概率参数。很高兴知道!无论如何,感谢您的输入,对于非加权示例非常有用。
ij = np.random.randint(p.shape[0], size=(p.ndim, 5)) # get 5 values
p[tuple(i for i in ij))]
>>> array([0.        , 0.        , 0.        , 0.11111111, 0.        ])