Generate random array of 0 and 1 with a specific ratio

后端 未结 4 2142
孤城傲影
孤城傲影 2021-02-19 06:09

I want to generate a random array of size N which only contains 0 and 1, I want my array to have some ratio between 0 and 1. For example, 90% of the array be 1 and the remainin

4条回答
  •  天涯浪人
    2021-02-19 06:26

    If you want an exact 1:9 ratio:

    nums = numpy.ones(1000)
    nums[:100] = 0
    numpy.random.shuffle(nums)
    

    If you want independent 10% probabilities:

    nums = numpy.random.choice([0, 1], size=1000, p=[.1, .9])
    

    or

    nums = (numpy.random.rand(1000) > 0.1).astype(int)
    

提交回复
热议问题