Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map values from a dataframe

I have a dataframe with the correspondence between two values:

enter image description here

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?

like image 569
Luis Ramon Ramirez Rodriguez Avatar asked Sep 03 '26 06:09

Luis Ramon Ramirez Rodriguez


2 Answers

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]
like image 57
Vaishali Avatar answered Sep 05 '26 13:09

Vaishali


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
like image 42
jezrael Avatar answered Sep 05 '26 13:09

jezrael