elviuz
elviuz

Reputation: 639

cast from list to numpy array problems in python

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

Upvotes: 4

Views: 559

Answers (2)

Daniel
Daniel

Reputation: 19537

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]])

Upvotes: 5

Aaron Hall
Aaron Hall

Reputation: 394815

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]])

Upvotes: 4

Related Questions