gpt4 book ai didi

python - 将数组的 numpy 数组转换为一个完整的 numpy 数组

转载 作者:太空狗 更新时间:2023-10-30 01:57:54 24 4
gpt4 key购买 nike

我想将我的数组数组变成一个数组。来自类似:

array([ array([[0, 0, 0, ..., 1, 0, 0],
[0, 1, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 2, 0, 0],
...,
array([[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 8, 0, 2],
...,
[0, 0, 0, ..., 0, 0, 0],
[1, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 1, 0, 0]], dtype=uint8)], dtype=object)

大小为 (10,) 的 3D numpy 数组大小为 (10,518, 32)

array([[[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0]]], dtype=uint8)

我试过将所有内容转换成列表,然后执行 np.asarray 并尝试将所有内容定义为相同的 dtype=uint8 但我无法将其转换为 3D 形式。

最佳答案

np.concatenate 应该可以解决问题:

创建一个数组的对象数组:

In [23]: arr=np.empty((4,),dtype=object)
In [24]: for i in range(4):arr[i]=np.ones((2,2),int)*i
In [25]: arr
Out[25]:
array([array([[0, 0],
[0, 0]]), array([[1, 1],
[1, 1]]),
array([[2, 2],
[2, 2]]), array([[3, 3],
[3, 3]])], dtype=object)

In [28]: np.concatenate(arr)
Out[28]:
array([[0, 0],
[0, 0],
[1, 1],
[1, 1],
[2, 2],
[2, 2],
[3, 3],
[3, 3]])

或者 reshape :

In [26]: np.concatenate(arr).reshape(4,2,2)
Out[26]:
array([[[0, 0],
[0, 0]],

[[1, 1],
[1, 1]],

[[2, 2],
[2, 2]],

[[3, 3],
[3, 3]]])
In [27]: _.shape
Out[27]: (4, 2, 2)

concatenate 有效地将其输入视为数组列表。因此,无论这是对象数组、列表还是 3d 数组,它都有效。

这不能简单地通过 reshape 来完成。 arr 是一个指针数组 - 指向位于内存中其他地方的数组。要获得单个 3d 数组,必须将所有部分复制到一个缓冲区中。这就是 concatenate 的作用 - 它创建一个大的空文件,并复制每个数组,但它是在编译代码中执行的。


np.array 不改变它:

In [37]: np.array(arr).shape
Out[37]: (4,)

但将 arr 视为数组列表确实有效(但比 concatenate 版本慢 - 数组更多地分析其输入)。

In [38]: np.array([x for x in arr]).shape
Out[38]: (4, 2, 2)

关于python - 将数组的 numpy 数组转换为一个完整的 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35192603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com