user11861166
user11861166

Reputation: 159

How to search a 2d array using 1d array to return the index 1 of the 2d array

I have a 2d(3,2) array and a 1d(3,1) array. Between the 2 they share a column of like values. I would like to search the 1d or 2d array for the like value and then return the corresponding element.

arr1=[0,a],[1,b],[2,c]

arr2=[2],[1],[0]

Expected outcome is =[c],[b],[a]

Upvotes: 0

Views: 130

Answers (2)

ToughMind
ToughMind

Reputation: 1009

You can use numpy array to do this.

import numpy as np

arr1 = [[0, 'a'], [1, 'b'], [2, 'c']]
arr2 = [[2], [1], [0]]

arr1 = np.array(arr1)
arr2 = np.array(arr2)
arr2 = np.squeeze(arr2)

res = arr1[arr2][:,1]

output

array(['c', 'b', 'a'], dtype='<U21')

Upvotes: 1

Dai
Dai

Reputation: 355

The following will return the "value" of an arbitrarily long list, arr1, with "keys" contained in arr1:

for line in arr1:
    if line[0] in arr2:
        print(line[1])

Upvotes: 0

Related Questions