使用两个参数的函数将两个numpy数组合并为矩阵

时间:2018-11-19 00:05:50

标签: python numpy matrix scipy

我大概要转换这个(非numpy的)for循环:

N = len(left)
M = len(right)
matrix = np.zeros(N, M)
for i in range(N):
  for j in range(M):
    matrix[i][j] = scipy.stats.binom.pmf(left[i], C, right[j])

有点像点积,但从数学上来说当然不是点积。我通常如何矢量化或制作类似pythonic / numpythonic的东西?

1 个答案:

答案 0 :(得分:3)

scipy.stats.binom.pmf 已被矢量化。但是,您必须 broadcast 以获得您想要的结果。

broadcast_out = scipy.stats.binom.pmf(left[:, None], C, right)

验证

np.random.seed(314)
left = np.arange(5, dtype=float)
right = np.random.rand(5)
C = 5

broadcast_out = scipy.stats.binom.pmf(left[:, None], C, right)

N = len(left)
M = len(right)
matrix = np.zeros((N, M))
for i in range(N):
  for j in range(M):
    matrix[i][j] = scipy.stats.binom.pmf(left[i], C, right[j])

print(np.array_equal(matrix, broadcast_out))

True