VOOZH about

URL: https://www.geeksforgeeks.org/python/find-the-number-of-rows-and-columns-of-a-given-matrix-using-numpy/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 18 Apr, 2026

In NumPy, determining dimensions of a matrix is a common task. Knowing number of rows and columns helps in data manipulation, analysis and reshaping operations. Below are the different methods to find the number of rows and columns of a matrix efficiently.

Using .shape Attribute

The .shape attribute of a NumPy array returns a tuple containing the number of rows and columns.


Output
('Rows:', 2)
('Columns:', 3)

Explanation:

  • np.array([[9, 9, 9], [8, 8, 8]]) creates a 2x3 matrix.
  • m.shape returns a tuple (2, 3).
  • Tuple unpacking rows, cols = m.shape assigns rows and columns to separate variables.

Using Indexing

Indexing can be used to obtain the number of rows and columns by accessing the elements of the .shape tuple.


Output
('Rows:', 2)
('Columns:', 3)

Explanation:

  • .shape[0] gives the number of rows.
  • .shape[1] gives the number of columns.
  • Printing them shows Rows: 2 and Columns: 3.

Using numpy.reshape()

reshape() is primarily used to change the shape of an array, but it can also help visualize dimensions by converting a 1D array into a 2D matrix.


Output
[[1 2 3]
 [4 5 6]
 [7 8 9]]
('Rows:', 3)
('Columns:', 3)

Explanation:

  • np.arange(1, 10) creates a 1D array [1,2,3,4,5,6,7,8,9].
  • .reshape((3,3)) converts it into a 3x3 matrix.
  • .shape returns (3, 3), which is unpacked into rows and cols.
Comment