Python array to 1-D Vector

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]

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

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

Tags:

Python

Numpy