简体   繁体   English

numpy:如何将(N,)维向量插入(N,M,D)维数组作为沿D轴的新元素? (N,M,D + 1)

[英]Numpy: how to insert an (N,) dimensional vector to an (N, M, D) dimensional array as new elements along the D axis? (N, M, D+1)

a is an array of shape (N, M, D) == (20, 4096, 6) . a是形状(N, M, D) == (20, 4096, 6)的数组。

b is an array of shape (N,) == (20,) . b是形状(N,) == (20,)的数组。

I would like to insert the values of b to a such that each value in b is appended element-wise to the D dim in a (7th element in a ). 我想的值插入ba使得每个值b被附加逐元素到D暗淡在a (在第七元件a )。

So c would be such an array, of shape (20, 4096, 7) , where c[i,:,-1] == b[i] for all i , and c[...,:-1] == a . 因此, c将是一个形状为(20, 4096, 7)的数组,其中c[i,:,-1] == b[i]对于所有i ,而c[...,:-1] == a

I know you could just make a new array and add the values accordingly eg: 我知道您可以制作一个新数组并相应地添加值,例如:

N, M, D = a.shape # (20, 4096, 6)
c = np.zeros((N, M, D+1))
c[...,:-1] = a
for i in range(N):
    c[i,:,-1] = b[i]

But was wondering if one of the numpy wizards here had a more slick way of doing this with numpy ops and no intermediate arrays. 但是想知道这里的numpy向导中是否有一个使用numpy ops且没有中间数组的更灵活的方法。

Replicate b along the second axis after extending it to 3D and then concatenate with a along the last axis - b延伸到3D之后,沿第二个轴复制b ,然后沿最后一个轴与a串联-

b_rep = np.repeat(b[:,None,None],a.shape[1],axis=1)
out = np.concatenate((a, b_rep,axis=-1)

Alternatively, we can use np.broadcast_to to create the replicated version : 另外,我们可以使用np.broadcast_to来创建复制版本:

b_rep = np.broadcast_to(b[:,None,None], (len(b), a.shape[1],1)

Here is another one-liner 这是另一条线

np.r_['2,3,0', a, np.broadcast_to(b, (a.T.shape[1:])).T]

Also, I'd like to mention that your original method is actually close to the (or at least a) recommended way. 另外,我想提到您的原始方法实际上接近(或至少是)推荐的方法。 Just use empty instead of zeros and broadcasting instead of the loop: 只需使用empty而不是zeros并使用广播而不是循环:

res = np.empty((N,M,D+1), np.promote_types(a.dtype, b.dtype))
res[..., :-1], res[..., -1] = a, b[:, None]

... ...

And - just for fun - one more, which I expressly do not recommend. 而且-仅出于娱乐目的-还有一个,我明确不建议这样做。 Do not use this! 不要使用这个!

np.where(np.arange(D+1)<D, np.lib.stride_tricks.as_strided(a, (N,M,D+1), a.strides), b[:, None, None])

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

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