Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match two columns from two dataframe, if they match get the corresponding column value

I have two data Df1 and Df2.There are few rows in my Df1['Col2] which are empty. I want to fill this this blank row with corresponding value of Df2.

Df1
Col1 Col2
1    AA
2   
2   
2   
3    AC
3    AC

Df2
Cluster label
1        AA
2        AB
3        AC
4        AD

Desired Output

Col1    Col2
1       AA
2       AB
2       AB
2       AB
3       AC
3       AC

I am trying the below code, but not getting the result :

Df1['Col2'] =np.where((Df2['Cluster']==Df1['Col1']),Df2['label'],'No label found')

I can not use merge function as I have some other constraints as well.

like image 401
Aditya sharma Avatar asked Dec 20 '25 04:12

Aditya sharma


1 Answers

you can combine an apply with a condition on col2

df1{"col2"] = df1.apply(lambda x: df2[df2['Cluster'] == x ['col1']]['label'].tolist()[0] if x['col2'] is None else x['col2'], axis = 1)
like image 138
Hicham Zouarhi Avatar answered Dec 21 '25 20:12

Hicham Zouarhi