mardi 14 juin 2016

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?


Aucun commentaire:

Enregistrer un commentaire