Abhishek Thakur Abhishek Thakur - 1 month ago 8
Python Question

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]

Answer
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
Comments