1
votes

I have 2 data frames: In each data frame i have column with the same name and values (Key_Merge1) and in each data frame i have 2 different column names with same values (Key_Merge2). How can i merge 2 data frames by 2 columns: 1. By Key Merge1 2. By Key Merge21 (DF1) and Key Merge22 (DF2)

DF1

PRODUCT PARAMETER_NAME  PARAMETER VALUE1    PARAMETER_VALUE2    PARAMETER_VALUE_3
AAA PARAM1  10  10  10
AAA PARAM2  11  11  11
BBB PARAM1  12  12  12
BBB PARAM2  12  12  12

DF2

PRODUCT_GROUP   PARAMETER_NAME  Limit1  Limit2  Limit3
AAA PARAM1  22  24  26
AAA PARAM2  32  34  36
BBB PARAM1  42  44  46
BBB PARAM2  52  54  56

DF1+DF2

PRODUCT PARAMETER_NAME  PARAMETER VALUE1    PARAMETER_VALUE2    PARAMETER_VALUE_3   Limit1  Limit2  Limit3
AAA PARAM1  10  10  10  22  24  26
AAA PARAM2  11  11  11  32  34  36
BBB PARAM1  12  12  12  42  44  46
BBB PARAM2  12  12  12  52  54  56

Thank you

1
Can you post an example data and df, your text description is not clear enough but generally you want to merge and pass the list of cols to merge the ;hs and rhs on: pd.merge(df1, df2, left_on=['Key_Merge1', 'Key_Merge21'], right_on=['Key_Merge1', 'Key_merge22'])EdChum
Thank yo a lot EdChum:Felix
Are you saying my code snippet worked?EdChum

1 Answers

0
votes

OK, you have to rename 'PRODUCT_GROUP' in DF2 in order for the merge to work:

In [34]:
pd.merge(df1, df2.rename(columns={'PRODUCT_GROUP':'PRODUCT'}))

Out[34]:
   PRODUCT PARAMETER_NAME  PARAMETER VALUE1  PARAMETER_VALUE2  \
0      AAA         PARAM1                10                10   
1      AAA         PARAM2                11                11   
2      BBB         PARAM1                12                12   
3      BBB         PARAM2                12                12   

   PARAMETER_VALUE_3  Limit1  Limit2  Limit3  
0                 10      22      24      26  
1                 11      32      34      36  
2                 12      42      44      46  
3                 12      52      54      56  

the merge will naturally find the 2 columns that match and perform an inner merge as desired