The shape attribute of a NumPy array returns a tuple representing the dimensions of the array. For a two-dimensional array, the shape tuple contains two values: the number of rows and the number of columns.
Example 1: Using .shape Attribute
Here we are finding the number of rows and columns of a given matrix using Numpy.shape.
Python
import numpy as npÂ
matrix = np.array([[9, 9, 9], [8, 8, 8]])Â
dimensions = np.shape(matrix)rows, columns = dimensionsÂ
print("Rows:", rows)print("Columns:", columns) |
Output:
Rows: 2
Columns: 3
Here we are using numpy.reshape() to find number of rows and columns of a matrix.
Python
import numpy as npÂ
Â
matrix= np.arange(1,10).reshape((3, 3))Â
# Original matrixprint(matrix)Â
# Number of rows and columns of the said matrixprint(matrix.shape) |
Output:
[[1 2 3]
[4 5 6]
[7 8 9]]
(3,3)
Example 2: Using Indexing
Here we are finding the number of rows and columns of a given matrix using Indexing.
Python
import numpy as npÂ
matrix = np.array([[4, 3, 2], [8, 7, 6]])rows = matrix.shape[0]columns = matrix.shape[1]Â
print("Rows:", rows)print("Columns:", columns) |
Output:
Rows: 2
Columns: 3
