Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding the number of rows and columns in a given matrix using Numpy
NumPy provides several ways to find the dimensions of a matrix. The most common method is using the shape attribute, which returns a tuple containing the number of rows and columns.
Creating a Matrix
First, let's create a NumPy matrix to work with ?
import numpy as np
# Create a 2x3 matrix with random numbers
matrix = np.random.rand(2, 3)
print("Matrix:")
print(matrix)
Matrix: [[0.37454012 0.95071431 0.73199394] [0.59865848 0.15601864 0.15599452]]
Finding Rows and Columns Using shape
The shape attribute returns a tuple where the first element is the number of rows and the second is the number of columns ?
import numpy as np
matrix = np.random.rand(2, 3)
print("Matrix shape:", matrix.shape)
print("Number of rows:", matrix.shape[0])
print("Number of columns:", matrix.shape[1])
Matrix shape: (2, 3) Number of rows: 2 Number of columns: 3
Alternative Methods
Using size and ndim
You can also use size for total elements and ndim for dimensions ?
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print("Shape:", matrix.shape)
print("Total elements:", matrix.size)
print("Number of dimensions:", matrix.ndim)
Shape: (2, 3) Total elements: 6 Number of dimensions: 2
Using len() for Rows
For the number of rows only, you can use len() ?
import numpy as np
matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print("Number of rows using len():", len(matrix))
print("Number of columns:", matrix.shape[1])
Number of rows using len(): 3 Number of columns: 4
Comparison
| Method | Returns | Best For |
|---|---|---|
matrix.shape |
Tuple (rows, cols) | Both dimensions |
len(matrix) |
Number of rows | Just row count |
matrix.size |
Total elements | Total element count |
Conclusion
Use matrix.shape to get both rows and columns as a tuple. For just the row count, len(matrix) is simpler. The shape attribute is the most versatile method for matrix dimensions.
Advertisements
