Home > Software engineering >  Combinig two numpy arrays of different dimensions
Combinig two numpy arrays of different dimensions

Time:07-22

I want to add one numpy array two another so it will look like this:

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

output:

[[3, 4], [[6, 5], [2, 1]]]

It should look like the output above and not like [[3,4],[6,5],[2,1]].

How do I do that with numpy arrays?

CodePudding user response:

Work with pure python lists, and not numpy arrays.

It doesn't make sense to have a numpy array holding two list objects. There's literally no gain in doing that.


If you directly instantiate an array like so:

np.array([[3, 4], [[6, 5], [2, 1]]])

You get

array([[3, 4],
       [list([6, 5]), list([2, 1])]], dtype=object)

which is an array with dtype=object. Most of numpy's power is lost in this case. For more information on examples and why, take a look at this thread.


If you work with pure python lists, then you can easily achieve what you want:

>>> a   b
[[3, 4], [[6, 5], [2, 1]]]

CodePudding user response:

Numpy as built-in stack commands that are (in my opinion) slightly easier to use:

>>> a = np.array([3, 4])
>>> b = np.array([[6, 5], [2, 1]])
>>> np.row_stack([b, a])
array([[3, 4],
       [6, 5],
       [2, 1]])

There's also a column stack. Ref: https://numpy.org/doc/stable/reference/generated/numpy.ma.row_stack.html

CodePudding user response:

You can't stack arrays of different shapes in one array the way you want (or you have to fill in gaps with NaNs or zeroes), so if you want to iterate over them, consider using list.

a = np.array([3, 4])
b = np.array([[6, 5], [2, 1]])
c = [a, b]
for arr in c:
    ...

If you still want a numpy array, you can try this:

>>> a = np.array([3, 4])
>>> b = np.array([[6, 5], [2, 1]])
>>> a.resize(b.shape,refcheck=False)
>>> c = np.array([a, b])

array([[[3, 4],
        [0, 0]],

       [[6, 5],
        [2, 1]]])
  • Related