0

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]])
1
  • 3
    Use: a.ravel().tolist() Commented Dec 17, 2022 at 1:45

2 Answers 2

1

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

Comments

0

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]

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.