简体   繁体   English

np.tile重复一维数组

[英]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 . 我有一个ndarray A ,我想将此ndarray元素明智地乘以另一个1D数组b ,其中我假设A.shape[i] = len(b)对于某些i I need this generality in my application. 我的应用程序需要这种通用性。

I can do this using np.tile as follows: 我可以使用np.tile做到这np.tile ,如下所示:

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: 对于i任何值,请尝试以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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