Tohiko Tohiko - 4 months ago 7x
Python Question

np.tile to repeat an 1D array

I have an ndarray,

and I want to multiply this ndarray element wise by another 1D array
where I assume that
A.shape[i] = len(b)
for some
. I need this generality in my application.

I can do this using
as follows:

A = np.random.rand(2,3,5,9)
b = np.random.rand(5)
i = 2
b_shape = np.ones(len(A.shape),
b_shape[i] = len(b)
b_reps = list(A.shape)
b_reps[i] = 1
B = np.tile(b.reshape(b_shape), b_reps)

# Here B.shape = A.shape and
# B[i,j,:,k] = b for all i,j,k

This strikes me as ugly. Is there a better way to do this?


For this particular example, the following code would do the trick:

result = A*b[:, np.newaxis]

For any value of i, try this:

A2, B = np.broadcast_arrays(A, b)
result = A2*B