【问题标题】:dataframe merge on left adding extra rows左侧的数据框合并添加额外的行
【发布时间】:2020-04-21 17:29:05
【问题描述】:

我从 csv 文件创建了一个发票数据框和一些主数据框

invoice=pd.read_csv('rocaInv4.csv')

soMstr=pd.read_csv('salesOfficeMstr.csv')
custFreightMstr=pd.read_csv('customerCodeFreightMstr.csv')
ratesMstr=pd.read_csv('freightMstr.csv')
pfep=pd.read_csv('pfepMstr.csv')

我根据物料主数据和客户主数据中的可用性删除了一些行。我每次都重新索引。

#checking availability of material
invoice=invoice[invoice['Material'].isin(pfep['Material'])]
invoice=invoice.reset_index(drop=True)

#checking availability of customer details
invoice=invoice[invoice['Ship to Party'].isin(custFreightMstr['Cust No'])]
invoice=invoice.reset_index(drop=True)

#checking validity of sales code
invoice=invoice[invoice['Sales Office'].isin(soMstr['Code'])]
invoice=invoice.reset_index(drop=True)

invoice.shape
#(384, 22)

然后我需要将数据从 master 复制到最终的、干净的 Invoice DataFrame。我没有对两个数据框进行 for 循环,而是对选择的列进行合并。

invoice1=invoice.merge(custFreightMstr[['Cust No','City','Customer Frgt Code']],left_on='Ship to Party',right_on='Cust No', how='left').drop_duplicates()

invoice1.shape
#(388, 25)

即使我在左侧合并,我最终也会多出 4 行。我可以确定哪些行已重复。但我无法确定原因。我在这里做错了什么?

【问题讨论】:

  • 对于一个Ship to Party,您可能在左侧有多个Cust No,因此您可能会获得更多行。没有看到数据就不能说太多,但最终数据框中有多少对 (Ship to Party, Cust No) 唯一的?
  • 啊!我以为主人是干净的。我检查并发现4重复,与增加的行完全相同。非常感谢!无论如何指定只使用合并中的第一个匹配项?所有这些都是样本数据,我无法控制它的干净程度
  • 您可以在合并之前根据键的重复值删除行。使用带有subset 参数的“drop_duplicates”。 pandas.pydata.org/pandas-docs/stable/reference/api/…

标签: python pandas merge


【解决方案1】:

您代码中的合并相当于left outer join。正如所讨论的,您有多个匹配键Cust No,其值为Ship to Party。删除主数据框中的重复键。这可能会有所帮助。

【讨论】:

    【解决方案2】:

    我不知道主框架中重复的Cust No 中哪个是正确的。出于编码目的,我执行了以下操作:

    #drop duplicate cust no in the master
    invoice1=invoice.merge(custFreightMstr.drop_duplicates('Cust No',keep='last')[['Cust No','City','Customer Frgt Code']],left_on='Ship to Party',right_on='Cust No', how='left',validate = 'm:1')
    

    'Cust No' 上的 drop_duplicate 删除所有重复项,仅保留最后一个条目。

    validate 关键字确认在实际合并期间每个 cust 代码只有一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-09
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2022-01-07
      相关资源
      最近更新 更多