12

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]
1
  • 2
    This doesn't actually look like numpy. Commented Aug 4, 2013 at 23:34

3 Answers 3

14
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
Sign up to request clarification or add additional context in comments.

Comments

8

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]

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.