Python

NumPy Np.Ndindex()

One of the most beneficial but straightforward indexing routines in NumPy is the npindex(). This routine provides us iterator that returns the indices of elements in an N-dimensional array.

This short article will discuss the ndindex() routine and its use in NumPy.

Syntax

The syntax of the ndindex routine is as shown:

1
class numpy.ndindex(*shape)

Parameters

It accepts the shape of the array as a scalar integer or tuple of integers.

Example #1

Consider the example shown below:

1
2
for index in np.ndindex(2,3):
    print(index)

In this case, we use the ndindex function to get the index of the elements in an array of shapes (2,3).

The above code should return:

1
2
3
4
5
6
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)

Example #2

We can also pass the shape as a single tuple. For example:

1
2
3
arr =  np.array([[1,2,3], [4,5,6]])
for index in np.ndindex((arr.shape)):
    print(index)

Here, we use the arr.shape property as the value of the ndindex() function.

Closing

In this one, we covered the ndindex() function in NumPy and how to use it. Feel free to explore the docs to learn more.

Happy coding!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list