31

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.

2
  • 2
    The example is already as flat as it can be (b.shape = (3,))! What exactly do you mean by flatten? Commented Jul 6, 2012 at 17:54
  • 1
    Yes, but practically, I want b to change into [1,2,3,3] Commented Jul 6, 2012 at 18:02

2 Answers 2

64

if you want [1,2,3,3], try this then

np.hstack(b)
Sign up to request clarification or add additional context in comments.

8 Comments

Nice. I was about to post this (which does the exact same thing): [x for bb in b for x in bb]
@urinieto actually the list comprehension-based method you posted is faster, although it's kinda nicer to have it settled in numpy's way.
how about for an array of 20k element?
@nye17 -- But at the end of the day, it's often nice to have a numpy array instead of a list.
@GökhanSever 20k wouldn't be a problem for modern computers, if you are really thresholded by speed in this kind of computation, I would say that you shouldn't have had an inhomogenous data array to begin with.
|
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.