Home > Software design >  Get a list from numpy ndarray in Python?
Get a list from numpy ndarray in Python?

Time:12-17

I have a numpy.ndarray here which I am trying to convert it to a list.

>>> a=np.array([[[0.7]], [[0.3]], [[0.5]]])

I am using hstack for it. However, I am getting a list of a list. How can I get a list instead? I am expecting to get [0.7, 0.3, 0.5].

>>> b = np.hstack(a)
>>> b
array([[0.7, 0.3, 0.5]])

CodePudding user response:

Do you understand what you have?

In [46]: a=np.array([[[0.7]], [[0.3]], [[0.5]]])    
In [47]: a
Out[47]: 
array([[[0.7]],

       [[0.3]],

       [[0.5]]])    
In [48]: a.shape
Out[48]: (3, 1, 1)

That's a 3d array - count the []

You can convert it to 1d with:

In [49]: a.ravel()
Out[49]: array([0.7, 0.3, 0.5])

tolist converts the array to a list:

In [50]: a.ravel().tolist()
Out[50]: [0.7, 0.3, 0.5]

You could also use a[:,0,0]. If you use hstack, that partially flattens it - but not all the way to 1d.

In [51]: np.hstack(a)
Out[51]: array([[0.7, 0.3, 0.5]])
In [52]: _.shape
Out[52]: (1, 3)
In [53]: np.hstack(a)[0]
Out[53]: array([0.7, 0.3, 0.5])

CodePudding user response:

Alternatively, numpy.ndarray.flatten can be used:

a.flatten().tolist()

And yet another possibility:

a.reshape(-1).tolist()

Output:

[0.7, 0.3, 0.5]
  • Related