简体   繁体   English

使用 Numpy 将多维数组相互附加/插入

[英]Appending/Inserting Multi-Dimension arrays into each other with Numpy

import pandas as pd
import numpy as np

x1 = np.random.randint(0,2000,(12,220,80))
x2 = np.random.randint(0,2000,(12,220,1000))

I currently have two 3-D arrays that I want to combine together to make a 4-D array and looking for the most efficient way我目前有两个 3-D 数组,我想将它们组合在一起以创建一个 4-D 数组并寻找最有效的方法

I want to combine them so they have the shape (12,220,81,1000) so that the x1 is repeated 1000 times appending each element of the second array onto the end of the first array.我想将它们组合起来,使它们具有 (12,220,81,1000) 形状,以便 x1 重复 1000 次,将第二个数组的每个元素附加到第一个数组的末尾。 I've tried different combinations of np.insert , np.concatenate and np.append along the various axes but can't seem to get it to produce the desired shape我已经尝试了沿各个轴的np.insertnp.concatenatenp.append不同组合,但似乎无法让它产生所需的形状

Thanks for any help in advance感谢您提前提供任何帮助

Make x1 a (12,220,80,1) and repeat on the last axis to get (12,220,80,1000).使x1 a (12,220,80,1) 并在最后一个轴上repeat以获得 (12,220,80,1000)。 Likewise expand x2 to (12,200,1,1000).同样将x2扩展到 (12,200,1,1000)。 Then you can concatenate on axis=2 .然后你可以在axis=2上连接。

the solution that worked following @hpaulj 's response.在@hpaulj 的回应之后起作用的解决方案。 It performed with 2.35 s ± 109 ms per loop.它以每个循环 2.35 s ± 109 ms 的速度执行。 If anyone is aware of anything quicker that would be amazing but this works great如果有人更快地意识到任何事情,那将是惊人的,但这很有效

x1_ = np.repeat(x1[:,:,:,None],np.shape(x2)[2],axis= -1)
x2_ = np.repeat(x2[:,:,None,:],1,axis = 2)
final = np.concatenate((x1_,x2_),axis = 2)

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

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