0

I have a array of list which

Input:

array([list([1, 1, 1]),
       list([1, 1, 1])],dtype=object)

I want to convert it to numpy nd-array:

Output:

array([[1., 1., 1.,],
       [1., 1., 1.,]])

I tried this code:

import numpy as np
npa = np.asarray(someListOfLists, dtype=np.float32)

But if failed.

2
  • can you try np.array? Also, what input are you using to cast to numpy? Commented Aug 25, 2021 at 15:06
  • @VivekKalyanarangan, if asarray doesn't work, why would array? Commented Aug 25, 2021 at 15:13

1 Answer 1

3

Constructing your array - simple copy-n-paste won't do it:

In [467]: a = np.array([None,None])
In [468]: a[:] = [1,2,3],[4,5,6]
In [469]: a
Out[469]: array([list([1, 2, 3]), list([4, 5, 6])], dtype=object)

YOur failed attempt, with full traceback:

In [471]: np.asarray(a, dtype=np.float32)
TypeError: float() argument must be a string or a number, not 'list'

The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "<ipython-input-471-a8170ed9d2a8>", line 1, in <module>
    np.asarray(a, dtype=np.float32)
ValueError: setting an array element with a sequence.

It's still trying to turn the 2 element object array into a 2 element float.

A working way:

In [472]: np.stack(a)
Out[472]: 
array([[1, 2, 3],
       [4, 5, 6]])

another

In [473]: a.tolist()
Out[473]: [[1, 2, 3], [4, 5, 6]]
In [474]: np.array(a.tolist())
Out[474]: 
array([[1, 2, 3],
       [4, 5, 6]])
Sign up to request clarification or add additional context in comments.

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.