0

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?

2
  • You get dtype='object' Commented Jul 21, 2022 at 17:59
  • What did you try? What the shape and dtype of the desired array? Commented Jul 21, 2022 at 18:57

3 Answers 3

2

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]]]
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

hank you :), but for me it is important that the two arrays will be combined two one array with two entries like: array([[3,4],[[6,5],[2,1]]] and not one array with three entries like you did
0

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]]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.