R 到 Python 元素明智逻辑条件下的翻译问题
R to Python translation problem in element wise logical condition
我在 R 中有以下代码:
N = 100 # number of data points
unifvec = runif(N)
d1 = rpois(sum(unifvec < 0.5),la1);d1
[1] 3 1 1 0 0 0 0 2 1 1 1 0 2 1 0 1 2 0 1 0 1 1 0 0 1 1 0 1 1 3 0
[32] 2 2 1 4 0 1 0 1 1 1 1 3 0 0 2 0 1 1 1 1 3
正在尝试将其翻译成 Python 我正在做 :
la1 = 1
N = 100 # number of data points
unifvec = np.random.uniform(0,1,N)
d1 = np.random.poisson(la1,sum(la1,unifvec < 0.5))
但我收到错误消息:
TypeError: 'int' object is not iterable
如何在 Python 中重现相同的结果?
sum
函数以错误的顺序接收参数。
将sum(la1,unifvec < 0.5)
更改为sum(unifvec < 0.5, la1)
后效果很好。
import numpy as np
la1 = 1
N = 100 # number of data points
unifvec = np.random.uniform(0, 1, N)
d1 = np.random.poisson(la1, sum(unifvec < 0.5, la1))
我在 R 中有以下代码:
N = 100 # number of data points
unifvec = runif(N)
d1 = rpois(sum(unifvec < 0.5),la1);d1
[1] 3 1 1 0 0 0 0 2 1 1 1 0 2 1 0 1 2 0 1 0 1 1 0 0 1 1 0 1 1 3 0
[32] 2 2 1 4 0 1 0 1 1 1 1 3 0 0 2 0 1 1 1 1 3
正在尝试将其翻译成 Python 我正在做 :
la1 = 1
N = 100 # number of data points
unifvec = np.random.uniform(0,1,N)
d1 = np.random.poisson(la1,sum(la1,unifvec < 0.5))
但我收到错误消息:
TypeError: 'int' object is not iterable
如何在 Python 中重现相同的结果?
sum
函数以错误的顺序接收参数。
将sum(la1,unifvec < 0.5)
更改为sum(unifvec < 0.5, la1)
后效果很好。
import numpy as np
la1 = 1
N = 100 # number of data points
unifvec = np.random.uniform(0, 1, N)
d1 = np.random.poisson(la1, sum(unifvec < 0.5, la1))