python look up list from one column and return equivalent id from different column

Viewed 51

Can anyone help with this approach please

lst=['a','b','c]

My input data frame

id name score
1   a    0.2
2   b    0.3
3   c    0.4
4   d    0.5

My output should be of list containing values as 1,2,3

res=[1,2,3]

So dataframe should look up equivalent values in lst if it matched it should return equivalent id

2 Answers

Use DataFrame.loc with test membership by Series.isin and then convert output Series to list:

lst=['a','b','c']
res = df.loc[df['name'].isin(lst), 'id'].tolist()
print (res)
[1, 2, 3]

If order of output is important and has to match values of list:

#for non matched values are created NaN
lst=['a','c','e','b']
res = df.set_index('name').reindex(lst)['id'].tolist()
print (res)
[1.0, 3.0, nan, 2.0]

#non matched values are removed
lst=['a','c','e','b']
res = df.set_index('name').reindex(lst)['id'].dropna().astype(int).tolist()
print (res)
[1, 3, 2]

To generate your list use:

df.set_index('name').id.loc[lst].tolist()
Related