gpt4 book ai didi

python - 具有不同形状元素的 numpy.array

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:58 26 4
gpt4 key购买 nike

我想要一个由另外两个数组组成的 numpy 数组(每个数组都有不同的形状)。据我所知,由于这个原因,必须在主数组的定义中使用:dtype = object

例如,让我们将数组定义(在 Python 2.7 中)

     a0 = np.arange(2*2).reshape(2,2)
a1 = np.arange(3*3*2).reshape(3,3,2)
b = np.array([a0,a1], dtype = object)

这很完美:b[1]a1 相同。但是,如果我将 a0 中的维度从 (2,2) 更改为 (3,3),就会发生一些奇怪的事情:

     a0 = np.arange(3*3).reshape(3,3)
a1 = np.arange(3*3*2).reshape(3,3,2)
b = np.array([a0,a1], dtype = object)

这次b[1]a1不相等,甚至形状不一样。这种奇怪行为的原因是什么?

也许对我来说有一个完全不同的解决方案。但我不想使用列表或元组,因为我想允许添加,例如 b + b。很明显,我可以为此目的编写自己的类,但有没有更简单的方法?

最佳答案

如果你明确想要一个对象数组,你可以先创建一个对象类型的空数组并赋值给它:

x = empty(5, dtype=object)
x[0] = zeros((3,3))
x[1] = zeros((3,2)) #does not merge axes.
x[2] = eye(4)
x[3] = ones((2,2))*2
x[4] = arange(10).reshape((5,2))

>>> x+x
array([array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]]),
array([[ 0., 0.],
[ 0., 0.],
[ 0., 0.]]),
array([[ 2., 0., 0., 0.],
[ 0., 2., 0., 0.],
[ 0., 0., 2., 0.],
[ 0., 0., 0., 2.]]),
array([[ 4., 4.],
[ 4., 4.]]),
array([[ 0, 2],
[ 4, 6],
[ 8, 10],
[12, 14],
[16, 18]])], dtype=object)

您必须先填充所有元素,然后才能执行算术运算,或者使用 np.append 从零开始增加元素。

关于python - 具有不同形状元素的 numpy.array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26453080/

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