1

I have a list of lists(have tuples inside) and want to convert it to a numpy array.

 Input: 
 [[1, 2, 3, (2, 4)], [3, 4, 8, 9], [2, 3, 5, (3, 7)]]
 Expected output:  
 array([[1, 2, 3, (2, 4)], [3, 4, 8, 9], [2, 3, 5, (3, 7)]])

I have tried np.array and np.asarray, but it raise an error: setting an array element with a sequence. Thanks for your help!

2
  • But is (2, 4) of dtype int32? Commented Oct 7, 2018 at 20:35
  • oh, i should delete that. dtype is not important for me Commented Oct 7, 2018 at 20:38

1 Answer 1

0

You can set the dtype to object.

>>> import numpy as np
>>> np.array([[1, 2, 3, (2, 4)], [3, 4, 8, 9], [2, 3, 5, (3, 7)]], dtype=object)
array([[1, 2, 3, (2, 4)],
       [3, 4, 8, 9],
       [2, 3, 5, (3, 7)]], dtype=object)

Note that there's probably not a good reason to create this array in the first place. The main strength of numpy is fast operations on flat sequences of numeric data, with dtype=object you are storing pointers to full fledged Python objects - just like in a list.

Here is a good answer explaining the object dtype.

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.