简体   繁体   中英

Map values from a dataframe

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 key s, 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM