Flatten numpy array
Question:
Is there a simple way in NumPy to flatten type object array?
I know .flatten() method flattens non-object type arrays constructed from same size arrays:
I1 a = np.array([[1],[2],[3]])
I2 a.flatten()
O2 array([1, 2, 3])
however, I can’t get dtype=object array flattened:
I4 b
O4 array([[1], [2, 3], [3]], dtype=object)
I5 b.flatten()
O5 array([[1], [2, 3], [3]], dtype=object)
Thanks.
Answers:
if you want [1,2,3,3], try this then
np.hstack(b)
In case when your array does not contain more than one nested array, np.hstack(arr)
function won’t work!
Workaround:
arr = np.array([[0]])
if arr.any():
arr = np.hstack(arr)
else:
arr = arr.flatten()
Is there a simple way in NumPy to flatten type object array?
I know .flatten() method flattens non-object type arrays constructed from same size arrays:
I1 a = np.array([[1],[2],[3]])
I2 a.flatten()
O2 array([1, 2, 3])
however, I can’t get dtype=object array flattened:
I4 b
O4 array([[1], [2, 3], [3]], dtype=object)
I5 b.flatten()
O5 array([[1], [2, 3], [3]], dtype=object)
Thanks.
if you want [1,2,3,3], try this then
np.hstack(b)
In case when your array does not contain more than one nested array, np.hstack(arr)
function won’t work!
Workaround:
arr = np.array([[0]])
if arr.any():
arr = np.hstack(arr)
else:
arr = arr.flatten()