I have a dataframe with the correspondence between two values:

A another list with only one of the variables:
l = ['a','b','c']
I want to make the mapping like:
df[l[0]]
and get 1
df[l[1]]
and get 2
As if it was a dictionary, how can I do that?
Are you looking for something like this?
df.loc[df['key']==l[0], 'value']
returns
0 1
1 1
Another way would be to set_index of the df to key.
df.set_index('key', inplace = True)
df.loc[l[0]].values[0]
Another way is map by Series or by dict but is necessary unique value of keys, drop_duplicates helps:
df = pd.DataFrame({'key':list('aabcc'),
'value':[1,1,2,3,3]})
s = df.drop_duplicates('key').set_index('key')['value']
print (s)
key
a 1
b 2
c 3
Name: value, dtype: int64
d = df.drop_duplicates('key').set_index('key')['value'].to_dict()
print (d)
{'c': 3, 'b': 2, 'a': 1}
l = ['a','b','c']
print (s[l[0]])
1
print (d[l[1]])
2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With