vendredi 29 mai 2015

Pandas copy values from other dataframe

Pandas dataframe df1 contains a list of values A

df1 = pd.DataFrame({'A':['a','a','b']})

   A
0  a
1  a
2  b

Dataframe df2 can be seen as mapping from values in A to values in B

df2 = pd.DataFrame({'A':['a','b'], 'B':[2,3]})

   A  B
0  a  2
1  b  3

I want to apply the mapping to df1. The working version I have is this one, but I feel there is potential for improvement, as I find my solution unreadable and I am unsure about how it would generalize to multiindexes

df2.set_index('A').loc[df1.set_index('A').index].reset_index()
   A  B
0  a  2
1  a  2
2  b  3

I could also convert df2 to a dictionary and use the replace method, but it does not convince me either.

Aucun commentaire:

Enregistrer un commentaire