4

I want to convert this list in a numpy array:

var=[array([ 33.85967782]), array([ 34.07298272]), array([ 35.06835424])]

The result should be the following:

[[ 33.85967782]
 [ 34.07298272]
 [ 35.06835424]]

but, if I type var = np.array(var), the result is the following:

[array([ 33.85967782]) array([ 34.07298272]) array([ 35.06835424])]

I have the numpy library: import numpy as np

0

2 Answers 2

5

np.vstack is the canonical way to do this operation:

>>> var=[np.array([ 33.85967782]), np.array([ 34.07298272]), np.array([ 35.06835424])]

>>> np.vstack(var)
array([[ 33.85967782],
       [ 34.07298272],
       [ 35.06835424]])

If you want a array of shape (n,1), but you have arrays with multiple elements you can do the following:

>>> var=[np.array([ 33.85967782]), np.array([ 35.06835424, 39.21316439])]
>>> np.concatenate(var).reshape(-1,1)
array([[ 33.85967782],
       [ 35.06835424],
       [ 39.21316439]])
Sign up to request clarification or add additional context in comments.

4 Comments

Traceback (most recent call last): File "/home/worm1988/Desktop/Tesi/appoggio.py", line 78, in <module> var = numpy.vstack(var) File "/usr/lib/python2.7/dist-packages/numpy/core/shape_base.py", line 226, in vstack return _nx.concatenate(map(atleast_2d,tup),0) ValueError: all the input array dimensions except for the concatenation axis must match exactly
@Elvio All elements of a numpy array must have the same shape, this is simply saying that all elements do not have the same shape. The data that you are working with appears to be different then what is shown, can you please update your post with relevant data.
@Ophion can you try with this data, please? gist.github.com/worm1988/9af484900aac7db3a5f1
@Elvio The very last array has two elements while all other arrays only have one element. Splitting the last array into two fixes the problem, works fine with np.vstack. Please see Another option in my post.
4

I don't know why your approach isn't working, but this worked for me:

>>> import numpy as np
>>> from numpy import array
>>> var=[array([ 33.85967782]), array([ 34.07298272]), array([ 35.06835424])]
>>> np.array(var)
array([[ 33.85967782],
       [ 34.07298272],
       [ 35.06835424]])

This also worked (fresh interpreter):

>>> import numpy as np
>>> var = [np.array([ 33.85967782]), np.array([ 34.07298272]), np.array([ 35.06835424])]
>>> np.array(var)
array([[ 33.85967782],
       [ 34.07298272],
       [ 35.06835424]])

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.