如何根据Python中每个元素的分布填充数组?

2024-05-29 02:11:13 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有3个盒子和3个动物,我想根据它们各自的分布创建一个盒子数组,每个盒子包含1个动物:

animals = ["Cat", "Dog", "Bunny"]
boxes = []

其中概率由

       "Cat"   "Dog"   "Bunny"
Box 1   0.3     0.4     0.3    
Box 2   0.2     0.3     0.5
Box 3   0.5     0.3     0.2

如何填充框数组,使第一个元素在概率0.3时等于“猫”,在概率0.4时等于“狗”,在概率0.3时等于“兔子”,第二个元素在概率0.2时等于“猫”,在概率0.3时等于“狗”,以此类推

另外,假设第一个元素/框是“Cat”。看看第二个和第三个方框,我们不能有一个概率>;再次更改第一个框的0,因为它已填充了一只猫。我们也不能有一个概率>;第二个包含cat的框的0再次出现,因为它已在框1中

通过将剩余的行/列缩放到1,但它们的比例仍然相同,是否可以负责任地解决此问题?例如,如果盒子1是一只猫,那么我们将得到

       "Cat"   "Dog"   "Bunny"
Box 1   1       0       0    
Box 2   0       0.4     0.6
Box 3   0       0.6     0.4

Tags: gtbox元素数组概率cat盒子动物
1条回答
网友
1楼 · 发布于 2024-05-29 02:11:13

您可以使用random.choices。它会自动为所选内容加权:

boxes = []

animals = ["Cat", "Dog", "Bunny"]
box1 = [0.3, 0.4, 0.3]
box2 = [0.2, 0.3, 0.5]
# box3 = [0.5, 0.3, 0.2] is commented out because it can be ignored

# Choose the first item to go in box1
boxes.append(random.choices(animals, k = 1, weights = box1))
chosen_ind = animals.index(boxes[0])

# Remove the chosen item from animals and box2
animals.pop(chosen_ind)
box2.pop(chosen_ind)

# Choose the second item
boxes.append(random.choices(animals, k = 1, weights = box2))
chosen_ind = animals.index(boxes[1])

# Remove the chosen item from animals, append the only remaining item
animals.pop(chosen_ind)
boxes.append(animals[0])

我很清楚,这不是一个特别干净、可扩展的解决问题的方法,但它在某种程度上解决了这个问题

编辑:这是一个带有numpy数组的新版本

import numpy as np

boxes = []

# n animals to choose from
animals = ['cat', 'dog', 'bunny' ... ]   # as many items as needed

# n x n matrix of probabilities
prob = np.array([
    [prob(box1, cat), prob(box1, dog), ...]
    [prob(box2, cat), prob(box2, dog), ...]
    ...
])

for box_ind, box in enumerate(prob):
    boxes.append(random.choices(animals, k = 1, weights = box)
    col_ind = animals.index(boxes[box_ind])
    
    # This line sets the probability of a chosen item to 0 for future iterations
    prob[:, col_ind] = 0

相关问题 更多 >

    热门问题