2

我已经看过这个问题并且我知道numpy.random.choice,但我的问题略有不同。

鉴于此,我有一个数据集如下:

dict ={"Number of polyps":[10,8,3,1,2,6,13],
        "Right ":[3,2,3,1,0,3,3],
        "Left":[2,2,4,15,6,7,1] }

dt = pd.DataFrame(dict)

所以,它是:

Number of polyps  Right   Left
            10       3     2
             8       2     2
             3       3     4
             1       1    15
             2       0     6
             6       3     7
            13       3     1

我需要按以下要求重新填充RightandLeft

  1. 和等于Right_LeftNumber of polyps
  2. Right和的值Left来自其当前值的加权概率

例如,对于如下给定的行:

Number of polyps  Right   Left
            10       3     2

所以,对于这一行,它可能如下所示。这里0.6= 3/(3+2)0.4= 2/(3+2)

nr = np.random.choice(["Right","Left"],size=10, replace=True,p=[0.6,0.4])
rightCount = list.count('Right')
leftCount = list.count('Left')
print(rightCount)
print(leftCount)

更新此行后将是:

Number of polyps  Right   Left
            10       3     7

问题是,我必须对数据集中的所有行都这样做,但我不知道该怎么做!

4

1 回答 1

5

您实际上是从二项式分布中提取的。它在 NumPy 中实现为numpy.random.binomial

>>> dt["Right"] = np.random.binomial(dt["Number of polyps"], dt["Right"]/(dt["Right"]+dt["Left"]))
>>> dt["Left"] = dt["Number of polyps"] - dt["Right"]

在这里,对于每一行,我们执行dt["Number of polyps"]二元选择试验,每个试验都Right以概率dt["Right"]/(dt["Right"]+dt["Left"])Left其他方式进行选择。

于 2019-09-29T19:11:16.767 回答