Behavior of numpy atleast_3d()



有人可以向我解释np.atleast_3d((的行为?

从使用np.atleast_2d((我认为与添加np.newaxis相似,同时将其传递给最后一个维度:

np.atleast_2d(3.0)
>>> array([[ 3.]])
np.atleast_2d([1.0, 2.0, 3.0])
>>> array([[1.0, 2.0, 3.0]])

但是np.atleast_3d((似乎行为完全不同

np.atleast_3d([[2.9, 3.0]])
>>> array([[[ 2.9],
            [ 3. ]]])

文档状态

For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1),
and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).

我希望(m,n(会成为(1,m,n(和(n,(成为(1,1,n,1(

这种行为是否误导了?

这是atleast_2d的摘录:

    if len(ary.shape) == 0:
        result = ary.reshape(1, 1)
    elif len(ary.shape) == 1:
        result = ary[newaxis,:]
    else:
        result = ary

因此,如果数组为1d。

,它使用newaxis技巧

3D:

    if len(ary.shape) == 0:
        result = ary.reshape(1, 1, 1)
    elif len(ary.shape) == 1:
        result = ary[newaxis,:, newaxis]
    elif len(ary.shape) == 2:
        result = ary[:,:, newaxis]
    else:
        result = ary

它也使用了newaxis技巧,但以不同的方式进行1和2D数组。它做了文档所说的。

还有其他改变形状的方法。例如,column_stack使用

array(arr, copy=False, subok=True, ndmin=2).T

expand_dims使用

a.reshape(shape[:axis] + (1,) + shape[axis:])

最新更新