我已经初始化了矩阵:
M = np.array(((),()))
M现在的形状为(2,0)。我希望按步骤填充M:首先添加1个数字,例如
M[0] = np.append(M[0],55)
通过此操作,我想获得这样的矩阵
((55),())
我该怎么做?我可以通过“ append”之类的标准pythons数组[]来做到这一点
arr = [[],[]]
arr[0].append(55)
但是在那之后,我需要将此数组作为一个numpy数组,并且要避免一种额外的类型转换操作。
答案 0 :(得分:1)
您写入的数组不是矩阵,因为其轴具有不同的尺寸。 你可以这样做
import numpy as np
x = np.zeros((2,1))
x[0][0] = 55
然后,如果要附加到它,可以执行以下操作:
x = np.append(x, [[42], [0]], axis=1)
请注意,要向矩阵附加除串联轴以外的所有尺寸,必须完全匹配
答案 1 :(得分:1)
我可以从2元素对象dtype数组开始:
In [351]: M = np.array((None,None))
In [352]: M.shape
Out[352]: (2,)
In [353]: M
Out[353]: array([None, None], dtype=object)
In [354]: M[0]=(5,)
In [355]: M[1]=()
In [356]: M
Out[356]: array([(5,), ()], dtype=object)
In [357]: print(M)
[(5,) ()]
或更直接地(从元组列表中)(请注意,有时这会产生错误而不是对象数组)。
In [362]: np.array([(55,),()])
Out[362]: array([(55,), ()], dtype=object)
但是我看不出有什么好处。构造元组列表会更容易:
In [359]: [(5,), ()]
Out[359]: [(5,), ()]
请勿尝试像列表追加一样使用np.append
。 np.concatenate
只是笨拙的前端。
M
在创建时是:
In [360]: M = np.array(((),()))
In [361]: M
Out[361]: array([], shape=(2, 0), dtype=float64)
它不能容纳任何元素。而且,您无法像使用列表一样更改插槽的形状。在numpy
中,shape
和dtype
有意义。
您可以指定object
dtype:
In [367]: M = np.array([(),()], object)
In [368]: M
Out[368]: array([], shape=(2, 0), dtype=object)
但是仍然无法引用和更改这0个元素之一。