Arrays Python Numpy Ndaray

Arrays Python Numpy Ndaray,arrays,numpy,Arrays,Numpy,我有3个代码片段: (1) x = array([[]]) #x.ndim=2 x=append(x,[[1,2]]) #after this, x.ndim=1??????????????????? x=append(x,[[3,4]],axis=0) #error b/c dimension (2) x = array([[]]) #x.ndim=2 x=append(x,[[1,2]],axis=0) #error b/c dimension??????????????

我有3个代码片段:

(1)

x = array([[]]) #x.ndim=2
x=append(x,[[1,2]]) #after this, x.ndim=1???????????????????
x=append(x,[[3,4]],axis=0) #error b/c dimension

(2)
    x = array([[]]) #x.ndim=2
    x=append(x,[[1,2]],axis=0) #error b/c dimension?????????????????

(3)
    x=append([[1,2]],[[3,4]],axis=0) #Good
(????????)是我不明白的部分。你能解释一下吗

我更喜欢(2),它是先声明一个由2个轴组成的numpy.ndarray,然后再附加数据。我该怎么做


谢谢。

来自附加文档:

Definition: append(arr, values, axis=None) Docstring: Append values to the end of an array. Parameters ---------- arr : array_like Values are appended to a copy of this array. values : array_like These values are appended to a copy of `arr`. It must be of the correct shape (the same shape as `arr`, excluding `axis`). If `axis` is not specified, `values` can be any shape and will be flattened before use. axis : int, optional The axis along which `values` are appended. If `axis` is not given, both `arr` and `values` are flattened before use. 定义:追加(arr,值,轴=无) 文档字符串: 将值附加到数组的末尾。 参数 ---------- arr:array_-like 值将附加到此数组的副本。 值:数组_-like 这些值被附加到“arr”的副本中。这一定是最重要的 形状正确(与'arr'形状相同,不包括'axis'。If`轴` 如果未指定,`values`可以是任何形状,并将被展平 使用前。 轴:int,可选 附加“值”的轴。如果未给出轴, “arr”和“values”在使用前都被展平。 也就是说,示例(1)失败的原因是,由于没有为第一次追加指定轴参数,x变平,因此第二次追加失败,因为形状不再匹配

第二个示例失败,因为形状不匹配。开始时,x.shape=(1,0),即1行0列。然后尝试添加一个沿第0轴具有形状(1,2)的数组(即,希望结果数组具有更多的行,但列数相同),这当然不起作用,因为列数不匹配

另外,我个人在使用numpy时几乎从不使用append()。预先分配正确的大小,然后使用切片来填充,比使用追加更有效,追加意味着每次都要重新分配和复制