heresthebuzz
heresthebuzz

Reputation: 708

Combining 2d numpy array "row-wise"

I have two 2d-arrays (but rows doesn't have same length) created with 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. 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. Any help will be appreciated.

Upvotes: 0

Views: 441

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

Let's use 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]]

Upvotes: 1

Related Questions