简体   繁体   中英

How to merge 2 dataframes based off of 2 different parameters pandas python

I have two different dataframes

df1 looks like this

 Item Number      UOM    Contract Cost    Quantity
  600543          CS        54.65           10
  300216          EA        45.79           15
  401799          CS        118.03          67 

df2

 Item Number     UOM    New Contract Cost     
   600543        EA           52.78
   300216        CS           42.90
   401799        CS           140.00

I need to merge the two dataframes so that if 'Item Number' and 'UOM' match, the two rows are combined. For the example dataframes above, my expected output would be:

df3

Item Number         UOM        Contract Cost    Quantity     New Contract Cost 
  401779            CS              118.03        67                140.00

If both parameters are not met, I don't want it included in the new dataframe. Very new to this. I have successfully done an inner merge based on a single column name, but can't figure out how to combine that second parameter. Thanks in advance!

that must be:

df3 = df1.merge(df2, on=["UOM","Item Number"])

Look at how "on" is defined here:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html

And by default, merge will do a inner join, so you will only have matching records

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM