Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten a numpy array of dtype object

Tags:

python

numpy

I'm taking ndarray slices with different length and I want my result to be flat. For example:

a = np.array(((np.array((1,2)), np.array((1,2,3))), (np.array((1,2)), np.array((1,2,3,4,5,6,7,8)))))

Is there any straight way to make this array flat by using numpy functionalities (without loop)?

like image 838
jgrynczewski Avatar asked Dec 18 '12 22:12

jgrynczewski


People also ask

How do I flatten a NumPy array?

By using ndarray. flatten() function we can flatten a matrix to one dimension in python. order:'C' means to flatten in row-major. 'F' means to flatten in column-major.

What does flatten () do in NumPy?

ndarray. flatten. Return a copy of the array collapsed into one dimension.


1 Answers

You could try flattening it and then using hstack, which stacks the array in sequence horizontally.

>>> a = np.array(((np.array((1,2)), np.array((1,2,3))), (np.array((1,2)), np.array((1,2,3,4,5,6,7,8)))))
>>> np.hstack(a.flatten())
array([1, 2, 1, 2, 3, 1, 2, 1, 2, 3, 4, 5, 6, 7, 8])
like image 87
NPE Avatar answered Sep 29 '22 00:09

NPE