pythonnumpynumpy-slicing

Numpy shape function


    A = np.array([
            [-1, 3],
            [3, 2]
        ], dtype=np.dtype(float))
    
    b = np.array([7, 1], dtype=np.dtype(float))
    

    print(f"Shape of A: {A.shape}")
    print(f"Shape of b: {b.shape}")

Gives the following output :

Shape of A: (2, 2)
Shape of b: (2,)

I was expecting shape of b to be (1,2) which is one row and two columns, why is it (2,) ?


Solution

  • Your assumption is incorrect, b only has one dimension, not two.

    b.ndim
    # 1
    

    To have a 2D array you would have needed an extra set of square brackets:

    b = np.array([[7, 1]], dtype=np.dtype(float))
    
    b.shape
    # (1, 2)
    
    b.ndim
    # 2
    

    Similarly for a 3D array:

    b = np.array([[[7, 1]]], dtype=np.dtype(float))
    
    b.shape
    # (1, 1, 2)
    
    b.ndim
    # 3
    

    Note that you can transform your original b into a 2D array with:

    b = np.array([7, 1], dtype=np.dtype(float))
    
    b.shape = (1, 2)
    
    b
    # array([[7., 1.]])
    

    Or:

    b = np.array([7, 1], dtype=np.dtype(float))[None]
    
    b.shape
    # (1, 2)
    
    b
    # array([[7., 1.]])