简体   繁体   中英

Python array to 1-D Vector

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]
In [15]: import numpy as np

In [16]: x = np.array([(9,), (1,), (1, 12), (9,), (8,)])

In [17]: np.concatenate(x)
Out[17]: array([ 9,  1,  1, 12,  9,  8])

Another option is np.hstack(x) , but for this purpose, np.concatenate is faster:

In [14]: x = [tuple(np.random.randint(10, size=np.random.randint(10))) for i in range(10**4)]

In [15]: %timeit np.hstack(x)
10 loops, best of 3: 40.5 ms per loop

In [16]: %timeit np.concatenate(x)
100 loops, best of 3: 13.6 ms per loop

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]

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

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