Home > database >  Lookup a Dataframe column with list and return list matching the row of another column?
Lookup a Dataframe column with list and return list matching the row of another column?

Time:03-26

What is the cleanest way to lookup a dataframe column using a query list and return answer list from another column of the same row?

df = pd.DataFrame({'Col1': ['A', 'B', 'C', 'D'], 
                   'Col2': [5, 6, 7, 8],
                   'Col3': [9, 10, 11, 12]
                    })

query = ['A', 'D', 'D', 'B', 'B']

Col2_result: [5, 8, 8, 6, 6]

Col3_result: [9, 12, 12, 10, 10]

CodePudding user response:

You could make Col1 the index and use .loc:

q = df.set_index('Col1').loc[query]

Output:

>>> q
      Col2  Col3
Col1            
A        5     9
D        8    12
D        8    12
B        6    10
B        6    1

>>> q['Col2'].tolist()
[5, 8, 8, 6, 6]

>>> q['Col3'].tolist()
[9, 12, 12, 10, 10]
  • Related