0

I have two dataframes with different sizes and I want to merge them.

It's like an "update" to a dataframe column based on another dataframe with different size.

This is an example input:

dataframe 1

  CODUSU Situação TIPO1
0    1AB        P    A0
1    2C3        C    B1
2    3AB        P    C1

dataframe 2

  CODUSU Situação  ABC
0    1AB        A    3
1    3AB        A    4

My output should be like this:

dataframe 3

  CODUSU Situação TIPO1
0    1AB        A    A0
1    2C3        C    B1
2    3AB        A    C1

PS: I did it through loop but I think there should better and easier way to make it!

I read this content: pandas merging 101 and wrote this code:

df3=df1.merge(df2, on=['CODUSU'], how='left', indicator=False)
df3['Situação'] = np.where((df3['Situação_x'] == 'P') & (df3['Situação_y'] == 'A') , df3['Situação_y'] , df3['Situação_x'])
df3=df3.drop(columns=['Situação_x', 'Situação_y','ABC'])
df3 = df3[['CODUSU','Situação','TIPO1']]

And Voilà, df3 is exactly what I needed! Thanks for everyone!

PS: I already found my answer, is there a better place to answer my own question?

1 Answers1

2
df1.merge(df2,how='left', left_on='CODUSU', right_on='CODUSU')

This should do the trick.

Also, worth noting that if you want your resultant data frame to not contain the column ABC, you'd use df2.drop("ABC") instead of just df2.

GLaw1300
  • 195
  • 9
  • That command returns this: >CODUSU Situação_x TIPO1 Situação_y ABC >0 1AB P A0 A 3.0 >1 2C3 C B1 NaN NaN >2 3AB P C1 A 4.0` – Lucas Dadalt Jul 22 '20 at 21:35