简体   繁体   English

“按行”组合二维 numpy 数组

[英]Combining 2d numpy array "row-wise"

I have two 2d-arrays (but rows doesn't have same length) created with numpy:我有两个用 numpy 创建的二维数组(但行的长度不同):

a = [[1,2,3,4,5],
     [6,7,8,9]]

b = [[1,2,30,40,50],
     [6,7,80,90,100]]

I would like to combine this two arrays into a new array, keeping the repeated values and adding the new ones "row-wise":我想将这两个数组组合成一个新数组,保留重复值并“按行”添加新值:

#desired output

c = [[1,2,3,4,5,30,40,50],
     [6,7,8,9,80,90,100]]

I tried many approaches, including np.apply_along_axis with np.unique or simply looping each row and appending to a list and then creating an array form that list.我尝试了很多方法,包括np.apply_along_axisnp.unique或者简单地循环每一行并附加到一个列表,然后从该列表中创建一个数组。 The closest result i got was an array of arrays, like so:我得到的最接近的结果是一个数组数组,如下所示:

array(array([1,2,3,4,5,30,40,50]), array([6,7,80,90,100]))

The above result isn't helpful, i need a numpy array.上面的结果没有帮助,我需要一个 numpy 数组。 Any help will be appreciated.任何帮助将不胜感激。

Let's use union :让我们使用union

[np.union1d(x,y) for x,y in zip(a,b)]

Output:输出:

[array([ 1,  2,  3,  4,  5, 30, 40, 50]),
 array([  6,   7,   8,   9,  80,  90, 100])]

If you really need list of lists:如果您确实需要列表列表:

[np.union1d(x,y).tolist() for x,y in zip(a,b)]

Output:输出:

[[1, 2, 3, 4, 5, 30, 40, 50], [6, 7, 8, 9, 80, 90, 100]]

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

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