【问题标题】:Merging two tables with different key columns合并具有不同键列的两个表
【发布时间】:2021-04-20 10:32:40
【问题描述】:

我有两个数据框AB,其中A 看起来像:

col1   col2 
USA    100
FR     99
UK     120

B 看起来像:

col1        colx 
USA teext    12
text FR      9
text UK      2

现在,我想使用col1 合并数据帧AB,结果是:

col1   col2  colx
USA    100    12
FR     99     9
UK     120    2

但是,您可以看到两个数据框中col1 列中的值并不完全相等。在 df B 中,值周围有更多文本,在合并两个数据框时我想忽略这些文本。有人知道如何在熊猫中使用merge 做到这一点吗?可能使用正则表达式?

【问题讨论】:

    标签: python pandas merge


    【解决方案1】:

    使用Series.str.extract 按列获取值df1['col1'] 到新列,所以可能merge

    pat = '|'.join(r"\b{}\b".format(x) for x in df1['col1'])
    df2['col11'] = df2['col1'].str.extract('('+ pat + ')', expand=False)
    print (df2)
            col1  colx col11
    0  USA teext    12   USA
    1    text FR     9    FR
    2    text UK     2    UK
    
    df = df1.rename(columns={'col1':'col11'}).merge(df2, on='col11')
    print (df)
      col11  col2       col1  colx
    0   USA   100  USA teext    12
    1    FR    99    text FR     9
    2    UK   120    text UK     2
    

    【讨论】:

      【解决方案2】:

      你是对的。我们不能直接mergeDataFrame。您必须使用Regular Expression 进行合并过程。在继续之前,合并DataFrame ADataFrame B 的基本需求是它们都包含Same ColumnSame Data。所以,为了实现这件事,你可以看到我们必须从DataFrame B 中获得trim 的额外内容。之后我们就可以方便的使用pd.merge()对其进行操作了。因此,相同场景的代码如下:-

      # Import all-important Libraries
      import pandas as pd
      import re
      
      # Reproducing given data of Column 'A'
      A = pd.DataFrame({
          'col1': ['USA', 'FR', 'UK'],   
          'col2': [100, 99, 120] 
      })
      
      # Print records of Column 'A'
      A
      
      # Output of Above Cell:-
          col1    col2
      0   USA     100
      1   FR      99
      2   UK      120
      
      # Reproducing given data of Column 'B'
      B = pd.DataFrame({
          'col1': ['USA teext', 'text FR', 'text UK'],   
          'colx': [12, 9, 2] 
      })
      
      # Print records of Column 'B'
      B
      
      # Output of Above Cell:-
          col1        colx
      0   USA teext   12
      1   text FR     9
      2   text UK     2
      

      DataFrame复现后,可以看到Country的模式已经在Capital格式中了。而我们必须trimtextSmall 格式。所以,我们可以使用re Library 来完成这个任务。

      # Find Pattern in Column'B' and Convert Dataset of Column 'B' Same as 'A'
      B.replace('[a-z ]','',regex = True, inplace = True)
      
      # Verify by Printing Records of 'B'
      B
      
      # Output of Above Cell:-
          col1    colx
      0   USA     12
      1   FR      9
      2   UK      2
      

      如您所见,我们终于实现了col1DataFrame Bcol1DataFrame A。所以,我们现在可以进行合并操作了:-

      # Finally you can now merge both 'DataFrame' Easily
      merged_df = pd.merge(left=A,right=B, left_on='col1', right_on='col1')
      
      # Print Merged 'DataFrame'
      merged_df
      
      # Output of Above Cell:-
          col1    col2    colx
      0   USA     100     12
      1   FR      99      9
      2   UK      120     2
      

      如您所见,我们已经实现了我们想要的Output。希望此解决方案对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-18
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-15
        • 1970-01-01
        相关资源
        最近更新 更多