Home > OS >  How to convert list object type in 3rd dimension of 3D numpy array?
How to convert list object type in 3rd dimension of 3D numpy array?

Time:10-30

A bit of background: Initially, I had the error ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list). after attempting to convert my_list into a tensor using tf.convert_to_tensor() .

I have a 3D numpy array my_list with the following properties:

enter image description here

As you can see in run [321] the 3rd dimension is a type list. I would like to convert it into a numpy.ndarray type too. Thank you!

CodePudding user response:

Make sure:

  • my_list only contains actual numbers, not other objects like a string
  • All entries of the same hierarchy have the same length, i.e. len(my_list[0]) == len(my_list[1])

To convert into an numpy array (in all dimensions at once):

my_array = np.array(my_list)

To replace a certain element with an array:

my_array[0][0] = np.array(my_array[0][0])

CodePudding user response:

Looks like my_list is a 3d object dtype array containing lists. np.array(my_list.tolist()) might return a 4d float array

tolist is a relatively fast way of creating a list (nested if necessary) of the root objects. np.array can than convert it to a numeric dtype array - assuming the root lists all have the same shape.

np.stack is also useful, but it only works if the object dtype array is 1d.

  • Related