Numpy shape function

47 views Asked by At
    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,) ?

2

There are 2 answers

2
mozway On BEST ANSWER

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.]])
1
Mahboob Nur On

You can try with reshape()

import numpy as np

b = np.array([7, 1],dtype=np.float64)
b = b.reshape(1, -1)  
print(f"Shape of b: {b.shape}")  # Output: (1, 2)

Or you can try with newaxis()

import numpy as np

b = np.array([7, 1], dtype=np.float64)
b = b[np.newaxis, :]  # Add a new axis to create a row vector
print(f"Shape of b: {b.shape}")  # Output: (1, 2)