In Numpy, how can I add a 1d array to a 2d array along a new axis

Viewed 33

Im sure this has been answered before as this seems like a pretty trivial question but I cant for the life of me figure out how to add a 2d array to a 1d array along the column so that there are two values in each row.

a = [[1,2,3], [1,3,5], [1,1,1]]
b = [[1], [2], [5]]

so what numpy function can I use to generate

[ [[1,2,3],[1]], [[1,3,5],[2]], [[1,1,1],[5]] ]

Cheers!

1 Answers

this isn't easy with numpy arrays, but you can get the structure you want with:

c = [list(q) for q in zip(a,b)]

# output
[[[1, 2, 3], [1]], [[1, 3, 5], [2]], [[1, 1, 1], [5]]]

casting this to a numpy array gives an array of lists, which is a strange structure and probably not very useful:

arr = np.array(c)

# output:
array([[list([1, 2, 3]), list([1])],
       [list([1, 3, 5]), list([2])],
       [list([1, 1, 1]), list([5])]], dtype=object)
Related