Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Values in Dataframe using a Lookup Dataframe

I want to replace values in the df dataframe using the lookup dataframe.

import pandas as pd

df=pd.DataFrame({
                  'no1':[20,20,40,10,50],
                  'no2':[50,20,10,40,50],
                  'no3':[30,10,50,40,50]
                  })

   no1  no2 no3
0   20  50  30
1   20  20  10
2   40  10  50
3   10  40  40
4   50  50  50

lookup=pd.DataFrame({'label':['A','B','C','D','E'],
                  'id':[10,20,30,40,50]})

    label id
0   A     10
1   B     20
2   C     30
3   D     40
4   E     50

Particularly, I'd like to have:

   no1  no2 no3
0   B   E   C
1   B   B   A
2   D   A   E
3   A   D   D
4   E   E   E

What is the best way doing it using pandas?

P.S.: I found a very similar question herein, but I do not quite follow as it is in R. A Python solution is appreciated.

like image 554
TwinPenguins Avatar asked Aug 31 '26 09:08

TwinPenguins


1 Answers

You could use replace with a dictionary:

import pandas as pd

df=pd.DataFrame({
                  'no1':[20,20,40,10,50],
                  'no2':[50,20,10,40,50],
                  'no3':[30,10,50,40,50]
                  })

lookup=pd.DataFrame({'label':['A','B','C','D','E'],
                  'id':[10,20,30,40,50]})

result = df.replace(dict(zip(lookup.id, lookup.label)))

print(result)

Output

  no1 no2 no3
0   B   E   C
1   B   B   A
2   D   A   E
3   A   D   D
4   E   E   E
like image 65
Dani Mesejo Avatar answered Sep 03 '26 00:09

Dani Mesejo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!