简体   繁体   中英

np.tile to repeat an 1D array

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

I can do this using np.tile as follows:

A = np.random.rand(2,3,5,9)
b = np.random.rand(5)
i = 2
b_shape = np.ones(len(A.shape), dtype=np.int)
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM