0

Suppose I have a numpy array e constructed as follow:

import numpy as np
a = np.array([1,2])
b = np.array([3,4])
c = np.array([5,6])
d = np.array([7,8])
e = np.empty((2,2), dtype=object)

e[0,0] = a
e[0,1] = b
e[1,0] = c
e[1,1] = d

>>> e
array([[array([1, 2]), array([3, 4])],
   [array([5, 6]), array([7, 8])]], dtype=object)

I don't know how to unpack the array e so that it becomes:

array([[1, 2, 3, 4],
   [5, 6, 7, 8]])

Any hint is appreciated.

7
  • Building an array like that e array in the first place is usually a mistake. Consider changing the code that produces e. Commented Jun 26, 2020 at 7:59
  • hello ito. I think what you're trying to do is "flatten" arrays which contain multiple arrays into one. You can use the + sign to combine two arrays, or checkout an existing stackoverflow question about flattening nested arrays. Commented Jun 26, 2020 at 8:18
  • @c8999c3f964f64 Adding two numpy arrays will try to broadcast them to compatible shapes, and add them elementwise. You cannot concatenate numpy arrays using +. Commented Jun 26, 2020 at 8:22
  • I was thinking of array([1, 2] + [3, 4]), are you sure this wouldnt work in numpy? sry for assuming otherwise! Commented Jun 26, 2020 at 8:27
  • @c8999c3f964f64 array([1,2] + [3,4]) is manipulation of lists not numpy.ndarrays. It works differently than array([1,2]) + array([3,4]) Commented Jun 26, 2020 at 8:55

2 Answers 2

4

Use numpy.block:

e = np.block([[a,b],[c,d]])
print(e)

Output:

array([[1, 2, 3, 4],
       [5, 6, 7, 8]])
Sign up to request clarification or add additional context in comments.

1 Comment

That is very nice. Looks like useful syntactic sugar for my convoluted vstack + hstack method.
1

You need to stack your arrays properly:

import numpy as np
a = np.array([1,2])
b = np.array([3,4])
c = np.array([5,6])
d = np.array([7,8])
e = np.vstack((np.hstack((a, b)), np.hstack((c, d))))

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.