Tohiko Tohiko - 1 year ago 151
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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download