I have two dataframe as shown below
|a|b|c|
|1|2| |
|4|5| |
|7|8| |
2nd dataframe is
|a_1|b_1|
|1 |5 |
|4 |2 |
|7 |8 |
I want to compare two common columns (a,a_1) and update the 3rd column in my 1st dataframe. Expected output is shown below
|a|b|c|
|1|2|5|
|4|5|2|
|7|8|8|
Is there a code to match common column and populate 3rd column?
CodePudding user response:
import pandas as pd
d1={
"a":(1,4,7),
"b":(2,5,8),
"c":(0,0,0)
}
d2={
"a_1": (1, 4, 7),
"b_1": (5, 2, 8)
}
df1=pd.DataFrame(d1)
df2=pd.DataFrame(d2)
# Iterate through each entry in a and compare it to a_1
for i in range(len(df1["a"])):
for j in range(len(df2["a_1"])):
if df1["a"][i] == df2["a_1"][j]:
df1["c"][i] = df2["b_1"][j]
