简体   繁体   English

如何在 3D numpy 数组的第 3 维中转换列表对象类型?

[英]How to convert list object type in 3rd dimension of 3D numpy array?

A bit of background: Initially, I had the error ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).一点背景:最初,我遇到错误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() .在尝试使用tf.convert_to_tensor()my_list转换为张量tf.convert_to_tensor()

I have a 3D numpy array my_list with the following properties:我有一个具有以下属性的 3D numpy 数组my_list

在此处输入图片说明

As you can see in run [321] the 3rd dimension is a type list .正如你在 run [321] 中看到的,第三维是一个类型list I would like to convert it into a numpy.ndarray type too.我也想将其转换为numpy.ndarray类型。 Thank you!谢谢!

Make sure:确保:

  • my_list only contains actual numbers, not other objects like a string my_list 只包含实际数字,不包含其他对象,如字符串
  • All entries of the same hierarchy have the same length, ie len(my_list[0]) == len(my_list[1])同一层次结构的所有条目具有相同的长度,即 len(my_list[0]) == len(my_list[1])

To convert into an numpy array (in all dimensions at once):要转换为 numpy 数组(一次在所有维度中):

my_array = np.array(my_list)

To replace a certain element with an array:用数组替换某个元素:

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

Looks like my_list is a 3d object dtype array containing lists.看起来my_list是一个包含列表的 3d object dtype数组。 np.array(my_list.tolist()) might return a 4d float array np.array(my_list.tolist())可能会返回一个 4d 浮点数组

tolist is a relatively fast way of creating a list (nested if necessary) of the root objects. tolist是一种创建根对象列表(必要时嵌套)的相对较快的方法。 np.array can than convert it to a numeric dtype array - assuming the root lists all have the same shape. np.array可以将其转换为数字 dtype 数组 - 假设根列表都具有相同的形状。

np.stack is also useful, but it only works if the object dtype array is 1d. np.stack也很有用,但它仅在对象 dtype 数组为 1d 时才有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM