Map values ​​from data frame

I have a dataframe with a match between two values:

enter image description here

Another list with only one of the variables:

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

      

I want to do the mapping like this:

df[l[0]] 

      

and get 1

df[l[1]] 

      

and get 2

As if it were a dictionary, how can I do this?

+3


source to share


2 answers


Are you looking for something like this?

df.loc[df['key']==l[0], 'value']

      

returns



0    1
1    1

      

Another way is to set the set_index of the df key.

df.set_index('key', inplace = True)
df.loc[l[0]].values[0]

      

+1


source


Another way is to map using Series

or dict

, but it needs a unique key

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

      

+1


source







All Articles