numpy atleast_3d()的行为

时间:2017-04-25 13:26:39

标签: python numpy

有人可以向我解释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)

这种行为是否具有误导性?

1 个答案:

答案 0 :(得分:2)

此处摘录自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:])