Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python array to 1-D Vector

Tags:

python

numpy

Is there a pythonic way to convert a structured array to vector?

For example:

I'm trying to convert an array like:

[(9,), (1,), (1, 12), (9,), (8,)]

to a vector like:

[9,1,1,12,9,8]
like image 568
Abhishek Thakur Avatar asked Aug 04 '13 23:08

Abhishek Thakur


2 Answers

Use numpy .flatten() method

>>> a = np.array([[1,2], [3,4]])
>>> a.flatten()
array([1, 2, 3, 4])
>>> a.flatten('F')
array([1, 3, 2, 4])

Source: Scipy.org

like image 179
PSN Avatar answered Oct 10 '22 21:10

PSN


You don't need to use any numpy, you can use sum:

myList = [(9,), (1,), (1, 12), (9,), (8,)]
list(sum(myList, ()))

result:

[9, 1, 1, 12, 9, 8]
like image 43
zs2020 Avatar answered Oct 10 '22 23:10

zs2020