How to replace values in column in one DataFrame by values from second DataFrame both have major key in Python Pandas?

Question:

I have 2 DataFrames in Python Pandas like below:

DF1

COL1 | ...  | COLn
-----|------|-------
A    | ...  | ...
B    | ...  | ...
A    | ...  | ...
.... | ...  | ...

DF2

G1  | G2
----|-----
A   | 1
B   | 2
C   | 3
D   | 4

And I need to replace values from DF1 COL1 by values from DF2 G2

So, as a result I need DF1 in formt like below:

COL1 | ...  | COLn
-----|------|-------
1    | ...  | ...
2    | ...  | ...
1    | ...  | ...
.... | ...  | ...

Of course my table in huge and it could be good to do that automaticly not by manually adjusting the values 🙂

How can I do that in Python Pandas?

Asked By: dingaro

||

Answers:

import pandas as pd

df1 = pd.DataFrame({"COL1": ["A", "B", "A"]}) # Add more columns as required
df2 = pd.DataFrame({"G1": ["A", "B", "C", "D"], "G2": [1, 2, 3, 4]})

df1["COL1"] = df1["COL1"].map(df2.set_index("G1")["G2"])

output df1:

   COL1
0     1
1     2
2     1
Answered By: Chrysophylaxs

you could try using the assign or update method of Dataframe:

import pandas as pd

df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df2 = pd.DataFrame({'B': [7, 8, 9]})

try

df1 = df1.assign(B=df2['B'])# assign will create a new Dataframe

or

df1.update(df2)# update makes a in place modification

here are links to the docs https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.assign.html

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.update.html

Answered By: Khan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.