简体   繁体   English

如何将数组从 dtype=object 转换为 dtype=np.int

[英]How to convert array from dtype=object to dtype=np.int

Currently, the array I got is目前,我得到的数组是

arr = array([array([ 2,  7,  8, 12, 14]), array([ 3,  4,  5,  6,  9, 10]),
   array([0, 1]), array([11, 13])], dtype=object)

How can I convert it into array([[ 2, 7, 8, 12, 14], [ 3, 4, 5, 6, 9, 10], [0, 1], [11, 13]]) ?如何将其转换为array([[ 2, 7, 8, 12, 14], [ 3, 4, 5, 6, 9, 10], [0, 1], [11, 13]])

I tried arr.astype(np.int) , but failed我试过arr.astype(np.int) ,但失败了

The dtype for an array of arrays will always be object .dtype为数组的数组将始终是object This is unavoidable because with NumPy only non-jagged n -dimensional arrays can be held in a contiguous memory block.这是不可避免的,因为使用 NumPy 只能将非锯齿状的n维数组保存在连续的内存块中。

Notice your constituent arrays are already of int dtype:请注意,您的组成数组已经是int dtype:

arr[0].dtype  # dtype('int32')

Notice also your logic will work for a non-jagged array of arrays:另请注意,您的逻辑将适用于非锯齿状数组数组:

arr = np.array([np.array([ 2,  7,  8]),
                np.array([ 3,  4,  5])], dtype=object)

arr = arr.astype(int)

arr.dtype  # dtype('int32')

In fact, in this case, the array of arrays is collapsed into a single array:事实上,在这种情况下,阵列的阵列被折叠成一个阵列:

print(arr)

array([[2, 7, 8],
       [3, 4, 5]])

For computations with a jagged array of arrays you may see some performance advantages relative to a list of lists, but the benefit may be limited.对于具有锯齿状数组数组的计算,您可能会看到相对于列表列表的一些性能优势,但优势可能有限。 See also How do I stack vectors of different lengths in NumPy?另请参阅如何在 NumPy 中堆叠不同长度的向量?

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

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