Friday, December 27, 2024
Google search engine
HomeLanguagesFind the number of rows and columns of a given matrix using...

Find the number of rows and columns of a given matrix using NumPy

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 matrix
print(matrix)
 
# Number of rows and columns of the said matrix
print(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

RELATED ARTICLES

Most Popular

Recent Comments