1

Roughly I want to convert this (non-numpy) for-loop:

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])

It's sort of like a dot product but of course mathematically not a dot product. How would I normally vectorize or make something like this pythonic/numpythonic?

1
  • It's np.zeros((N,M)). And better to index with arr[i, j]. Commented Nov 19, 2018 at 0:32

1 Answer 1

3

scipy.stats.binom.pmf already is vectorized. However, you have to broadcast your inputs in order to get your desired result.

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

Validation

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.