简体   繁体   中英

How to unpack nested numpy.ndarray?

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.

Use numpy.block :

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

Output:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM