如何根据条件语句使用 numpy.where() 修改数组?

问题描述 投票:0回答:1

我正在尝试使用 numpy 生成 60 个随机数的数组(

0
1
,即二项式的伯努利子集)。代码的第一部分工作正常,因为它生成 60 个随机值(基于给定概率的
0
1
值)。

但是,然后我想使用

numpy.where()
修改第一个存储数组的值(保存在“结果”中),这样对于每个元素,如果它是
1
,它就变成
"Z"
,如果它是
0
然后它被替换为另一个随机二项式数。

代码的多次迭代表明,它正在用

1
替换
"Z"
,但它并没有修改任何零,因为最终我应该在零所在的位置找到一些新的
1
,而这并没有发生。

import numpy

n = 50 #The number of times to repeat the run
p = 0.1
count = 0

# Day one of the simulation
result = numpy.random.binomial(1, p, 60) 
print (result)
for ele in result: 
        if (ele == 1):
            count = count +1
print ("Number Infected:", count)

# Create the matrix to track who is infected
result = numpy.where(result == 1, "Z", numpy.random.binomial(1,p*count))
count = 0
for ele in result: 
        if (ele == 1):
            count = count +1

# while count > 0: EVENTUALLY YOU WILL LOOP TO THIS CONDITION #
# ith day of simulation #
#for ele in result:
#        if (ele == 0):
#            ele == "X"
#        else:
#            ele == "I"
print(result)
print("Number Infected:", count)

当前结果:

[0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0]
Number Infected: 5
['0' 'Z' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' 'Z' '0' '0'
 '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0'
 '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' 'Z' 'Z'
 '0' '0' '0' 'Z' '0' '0']
Number Infected: 0
python numpy statistics
1个回答
0
投票

将 numpy.where() 行替换为:

new_values = numpy.random.binomial(1, p * count, size=result.size)
result = numpy.where(result == 1, "Z", new_values)

这将用一组新的随机值替换零。

© www.soinside.com 2019 - 2024. All rights reserved.