how do I match and find a vector in a Numpy array?

Question:

I have a Numpy array with size [2000,6].now I have an array with size [1,6] and I want to know which row of the main Numpy array is the same as this [1,6] array. if it exists in the main array, return the index of the row. for example row 1. but I do not want to use for loops because it is really time-consuming. I do not know how I can find a vector in an array and extract its related index. please help me with this issue. Thanks

Asked By: david

||

Answers:

this is what I have, though I imagine theres some method in np.arrays that could do this for you

import numpy as np
arr = np.array([[1, 2 ,3, 4, 5, 6],[7, 8 ,9, 1, 2, 1],[ 1, 2, 3, 4, 5 ,6]])
    for index in arr:
        if index == [7, 8 ,9, 1, 2, 1]:
            print(index)
Answered By: Christian Trujillo

Assuming you are using NumPy for this, your goal can be obtained by using the numpy.where method.

NumPy Solution

You can ignore this cell as I am just creating a simulated version of your problem:

# Simulate @david data
import numpy as np

target_row = np.array((7, 8, 9, 1, 2, 1))
simulated_array = np.zeros((2000, 6))

# I put the target row in index 3
simulated_array[3] = target_row
# Solution
import numpy as np

target_row = np.array((7, 8, 9, 1, 2, 1))
condition = simulated_array == target_row
where_result = np.where(condition)

# This is required since a row of indices is returned above
target_index = where_result[0]

Python List solution

# Simulate @david array

simulated_list = array.tolist()
target_list = [7, 8, 9, 1, 2, 1]
# Solution
target_list = [7, 8, 9, 1, 2, 1]
target_index = simulated_list.index(target_list)

Resources

numpy.wherehttps://numpy.org/doc/stable/reference/generated/numpy.where.html

Answered By: Jesse H.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.