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!

Cindy
  • 43
  • 1
  • 7

1 Answers1

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.

timgeb
  • 76,762
  • 20
  • 123
  • 145