Python numpy find index element

Python numpy find index element

  • Numpy | Array Creation
  • numpy.arange() in Python
  • numpy.zeros() in Python
  • Create a Numpy array filled with all ones
  • numpy.linspace() in Python
  • numpy.eye() in Python
  • Creating a one-dimensional NumPy array
  • How to create an empty and a full NumPy array?
  • Create a Numpy array filled with all zeros | Python
  • How to generate 2-D Gaussian array using NumPy?
  • How to create a vector in Python using NumPy
  • Python | Numpy fromrecords() method
  • Copy and View in NumPy Array
  • How to Copy NumPy array into another array?
  • Appending values at the end of an NumPy array
  • How to swap columns of a given NumPy array?
  • Insert a new axis within a NumPy array
  • numpy.hstack() in Python
  • numpy.vstack() in python
  • Joining NumPy Array
  • Combining a one and a two-dimensional NumPy Array
  • Python | Numpy np.ma.concatenate() method
  • Python | Numpy dstack() method
  • Splitting Arrays in NumPy
  • How to compare two NumPy arrays?
  • Find the union of two NumPy arrays
  • Find unique rows in a NumPy array
  • Python | Numpy np.unique() method
  • numpy.trim_zeros() in Python
  • Matrix manipulation in Python
  • numpy matrix operations | empty() function
  • numpy matrix operations | zeros() function
  • numpy matrix operations | ones() function
  • numpy matrix operations | eye() function
  • numpy matrix operations | identity() function
  • Adding and Subtracting Matrices in Python
  • Matrix Multiplication in NumPy
  • Numpy ndarray.dot() function | Python
  • NumPy | Vector Multiplication
  • How to calculate dot product of two vectors in Python?
  • Multiplication of two Matrices in Single line using Numpy in Python
  • Python | Numpy np.eigvals() method
  • How to Calculate the determinant of a matrix using NumPy?
  • Python | Numpy matrix.transpose()
  • Python | Numpy matrix.var()
  • Compute the inverse of a matrix using NumPy
  • Reshape NumPy Array
  • Python | Numpy matrix.resize()
  • Python | Numpy matrix.reshape()
  • NumPy Array Shape
  • Change the dimension of a NumPy array
  • numpy.ndarray.resize() function – Python
  • Flatten a Matrix in Python using NumPy
  • numpy.moveaxis() function | Python
  • numpy.swapaxes() function | Python
  • Python | Numpy matrix.swapaxes()
  • numpy.vsplit() function | Python
  • numpy.hsplit() function | Python
  • Numpy MaskedArray.reshape() function | Python
  • Python | Numpy matrix.squeeze()
  • Random sampling in numpy | ranf() function
  • Random sampling in numpy | random() function
  • Random sampling in numpy | random_sample() function
  • Random sampling in numpy | sample() function
  • Random sampling in numpy | random_integers() function
  • Random sampling in numpy | randint() function
  • numpy.random.choice() in Python
  • How to choose elements from the list with different probability using NumPy?
  • How to get weighted random choice in Python?
  • numpy.random.shuffle() in python
  • numpy.random.geometric() in Python
  • numpy.random.permutation() in Python
  • Numpy | Array Creation
  • numpy.arange() in Python
  • numpy.zeros() in Python
  • Create a Numpy array filled with all ones
  • numpy.linspace() in Python
  • numpy.eye() in Python
  • Creating a one-dimensional NumPy array
  • How to create an empty and a full NumPy array?
  • Create a Numpy array filled with all zeros | Python
  • How to generate 2-D Gaussian array using NumPy?
  • How to create a vector in Python using NumPy
  • Python | Numpy fromrecords() method
  • Copy and View in NumPy Array
  • How to Copy NumPy array into another array?
  • Appending values at the end of an NumPy array
  • How to swap columns of a given NumPy array?
  • Insert a new axis within a NumPy array
  • numpy.hstack() in Python
  • numpy.vstack() in python
  • Joining NumPy Array
  • Combining a one and a two-dimensional NumPy Array
  • Python | Numpy np.ma.concatenate() method
  • Python | Numpy dstack() method
  • Splitting Arrays in NumPy
  • How to compare two NumPy arrays?
  • Find the union of two NumPy arrays
  • Find unique rows in a NumPy array
  • Python | Numpy np.unique() method
  • numpy.trim_zeros() in Python
  • Matrix manipulation in Python
  • numpy matrix operations | empty() function
  • numpy matrix operations | zeros() function
  • numpy matrix operations | ones() function
  • numpy matrix operations | eye() function
  • numpy matrix operations | identity() function
  • Adding and Subtracting Matrices in Python
  • Matrix Multiplication in NumPy
  • Numpy ndarray.dot() function | Python
  • NumPy | Vector Multiplication
  • How to calculate dot product of two vectors in Python?
  • Multiplication of two Matrices in Single line using Numpy in Python
  • Python | Numpy np.eigvals() method
  • How to Calculate the determinant of a matrix using NumPy?
  • Python | Numpy matrix.transpose()
  • Python | Numpy matrix.var()
  • Compute the inverse of a matrix using NumPy
  • Reshape NumPy Array
  • Python | Numpy matrix.resize()
  • Python | Numpy matrix.reshape()
  • NumPy Array Shape
  • Change the dimension of a NumPy array
  • numpy.ndarray.resize() function – Python
  • Flatten a Matrix in Python using NumPy
  • numpy.moveaxis() function | Python
  • numpy.swapaxes() function | Python
  • Python | Numpy matrix.swapaxes()
  • numpy.vsplit() function | Python
  • numpy.hsplit() function | Python
  • Numpy MaskedArray.reshape() function | Python
  • Python | Numpy matrix.squeeze()
  • Random sampling in numpy | ranf() function
  • Random sampling in numpy | random() function
  • Random sampling in numpy | random_sample() function
  • Random sampling in numpy | sample() function
  • Random sampling in numpy | random_integers() function
  • Random sampling in numpy | randint() function
  • numpy.random.choice() in Python
  • How to choose elements from the list with different probability using NumPy?
  • How to get weighted random choice in Python?
  • numpy.random.shuffle() in python
  • numpy.random.geometric() in Python
  • numpy.random.permutation() in Python
Читайте также:  Java public interface enum

Источник

Find Index of Element in Numpy Array

In this tutorial, we will look at how to find the index of an element in a numpy array.

How to find the index of element in numpy array?

Get index of element of a numpy arrya

You can use the numpy’s where() function to get the index of an element inside the array. The following example illustrates the usage.

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 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.

Here, arr is the numpy array and i is the element for which you want to get the index. Inside the function, we pass arr==i which is a vectorized operation on the array arr to compare each of its elements with the value in i and result in a numpy array of boolean True and False values.

Now, np.where() gives you all the indices where the element occurs in the array. That is the indices of all the elements for which arr==i evaluates to True. This method works for both one-dimensional and multidimensional arrays. See the examples below:

1. Index of element in 1D array

Let’s apply the above syntax on a one-dimensional numpy array and find all the indices where a particular element occurs. First, let’s create a 1D array and print it out.

import numpy as np # create a numpy array arr = np.array([7, 5, 8, 6, 3, 9, 5, 2, 3, 5]) # print the original array print("Original array:", arr)
Original array: [7 5 8 6 3 9 5 2 3 5]

Now that we have a 1D numpy array, let’s find the indexes where the element 5 occurs inside the array:

# find index of 5 result = np.where(arr==5) # print the result print("Index of 5:", result)
Index of 5: (array([1, 6, 9], dtype=int64),)

We get a tuple of numpy arrays as an output. Note that this tuple only has one numpy array storing the indices of occurrence of the element 5 inside the array.

If you were to use the np.where() function on a multidimensional numpy array, the returned tuple would have multiple numpy arrays, one for each axis.

What if the element is not present in the array?

If the element is not present in the array we get an empty array with np.where() . For example, let’s use it to find the index of 1 , an element that is not present in the above array arr .

# index of 1 print(np.where(arr==1))

You can see that the returned tuple contains an empty numpy array.

Index of the first occurrence of element

Since np.where() returns all the indexes of the occurrence of an element. You can use it to find the index of the first occurrence. For example, let’s find the index of the first occurrence of 5 in the above array.

# the first index of 5 print("First index of 5:", np.where(arr==5)[0][0])

From the previous examples, we know that 5 is present at indexes 1, 6, and 9 in the array arr. Here we get its first occurrence which is at index 1.

2. Index of element in 2D array

We can also use the np.where() function to find the position/index of occurrences of elements in a two-dimensional or multidimensional array. For a 2D array, the returned tuple will contain two numpy arrays one for the rows and the other for the columns.

First, let’s create a two-dimensional numpy array.

# create a 2D numpy array arr = np.array([[21, 17, 19], [15, 23, 17], [17, 11, 16]]) # print the original array print("Original array:\n", arr)
Original array: [[21 17 19] [15 23 17] [17 11 16]]

Here we created a 2D numpy array with three rows and three columns. Let’s find the indexes where 17 occurs inside this array.

# find index of 17 result = np.where(arr == 17) # print the result print("Index of 17:", result)
Index of 17: (array([0, 1, 2], dtype=int64), array([1, 2, 0], dtype=int64))

The returned tuple from np.where() contains two numpy arrays. The first array values tell the row indexes whereas the second array values tell the column indexes of the occurrences of the element inside the 2D array.

Let’s make these indexes more readable by showing the (row, column) index tuples for each occurrence.

# get the position in the 2-d array print(list(zip(result[0], result[1])))

The result shows that 17 occurs at the following locations – row 0 column 1, row 1 column 2, and row 2 column 0 with the index for rows and columns starting from 0.

What if the element is not present in the array?

If the element is not present in the 2D array. The returned tuple from np.where() will have two empty numpy arrays. For example, if we check for the index of 13, an element that is not present in the 2D array above –

print("Index of 13:", np.where(arr==13))
Index of 13: (array([], dtype=int64), array([], dtype=int64))

We get a tuple of two empty numpy arrays.

For more on the numpy where function, refer to its documentation.

With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having numpy version 1.18.5

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

  • How to sort a Numpy Array?
  • Create Pandas DataFrame from a Numpy Array
  • Different ways to Create NumPy Arrays
  • Convert Numpy array to a List – With Examples
  • Append Values to a Numpy Array
  • Find Index of Element in Numpy Array
  • Read CSV file as NumPy Array
  • Filter a Numpy Array – With Examples
  • Python – Randomly select value from a list
  • Numpy – Sum of Values in Array
  • Numpy – Elementwise sum of two arrays
  • Numpy – Elementwise multiplication of two arrays
  • Using the numpy linspace() method
  • Using numpy vstack() to vertically stack arrays
  • Numpy logspace() – Usage and Examples
  • Using the numpy arange() method
  • Using numpy hstack() to horizontally stack arrays
  • Trim zeros from a numpy array in Python
  • Get unique values and counts in a numpy array
  • Horizontally split numpy array with hsplit()

Author

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

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

Оцените статью