Numpy atleast_3d () behavior

Can someone explain to me the behavior of np.atleast_3d ()?

From using np.atleast_2d (), I thought it was like adding np.newaxis, with whatever is passed to it last size:

np.atleast_2d(3.0)
>>> array([[ 3.]])

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

      

But np.atleast_3d () seems to behave very differently

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

      

The documentation states

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).

      

I would expect (M, N) to become (1, M, N) and (N,) to become (1, 1, N, 1)

Isn't that misleading?

+3


source to share


1 answer


Here's an excerpt from atleast_2d

:

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

      

So it uses the trick newaxis

if the array is 1d.

For 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

      



It also uses a trick newaxis

, but in different ways for 1 and 2d arrays. He does what the documents say.

There are other ways to change the shape. For example column_stack

uses

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

      

expand_dims

uses

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

      

+2


source







All Articles