Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 734
elviuz Avatar asked Jan 11 '23 23:01

elviuz


2 Answers

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]])
like image 184
Daniel Avatar answered Jan 18 '23 02:01

Daniel


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]])
like image 38
Russia Must Remove Putin Avatar answered Jan 18 '23 01:01

Russia Must Remove Putin