get the number of rows in a numpy array

Numpy – Get the Number of Rows of an Array

In this tutorial, we will look at how to get the number of rows of a 2D array in Numpy with the help of some examples.

How to get the number of rows in Numpy?

get the number of rows in a numpy array

You can use the Python built-in len() function or the numpy.ndarray.shape property to get the number of rows of a 2d Numpy array.

The following is the syntax –

# num rows using the len() function
len(ar)
# num rows using the .shape property
ar.shape[0]

Let’s now look at both the methods with the help of some examples –

First, we will create a 2d Numpy array that we will be using throughout this tutorial.

import numpy as np

# create a 2d array
ar = np.array([
    [1, 2, 3, 4],
    [1, 1, 0, 0],
    [5, 6, 7, 8]
])
# display the array
print(ar)

Output:

[[1 2 3 4]
 [1 1 0 0]
 [5 6 7 8]]

Here, we used the numpy.array() function to create a 2d array with three rows and four columns.

Method 1 – Number of rows using the len() function

len() is a Python built-in function that returns the length of an object. It is used on sequences or collections. If you apply the len() function on a 2d Numpy array, it will return the number of rows in the array.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

# number of rows of array
print(len(ar))

Output:

3

We get the number of rows in the above array as 3.

Method 2 – Number of rows using the .shape property

You can also get the number of rows in a 2d Numpy array by accessing its .shape property which returns the tuple (row_count, column_count). To only get the row count, access the value at the index 0 from the shape property.

# number of rows of array
print(ar.shape[0])

Output:

3

We get the same result as above, 3.

Summary

In this tutorial, we looked at two methods to get the row count for a 2d array in Numpy.

  1. Use the Python built-in len() function.
  2. Via the .shape property of the array. (Value at the 0th index of the shape tuple is the row count)

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj profile picture

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts
Scroll to Top