Reputation: 789
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
Upvotes: 2
Views: 58
Reputation: 30991
To generate your list use:
df.set_index('name').id.loc[lst].tolist()
Upvotes: 0
Reputation: 862761
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]
Upvotes: 1