【问题标题】:Merging two dataframes on some overlapping columns while keeping non-overlapping columns在某些重叠列上合并两个数据框,同时保持非重叠列
【发布时间】:2019-03-02 00:57:51
【问题描述】:

我目前有两个数据框:

df1:

     col1    col2   col3   col4
 0  Apple   store1    1      3
 1  Tree    store2    1      3
 2  Banana  store3    2      4
 3  Card    store4    2      4 ...

df2:

     col1    col2   col3   col4   col5   col6
 0  Apple   store1    1      3     123    50
 1  Tree    store2    1      3     451    32
 2  Mango   store2    2      4     313    15
 3  Guava   store5    2      4     113     9

如果前 4 列中的值相同,我想要将 df1 和 df2 合并在一起,但我想将 col5 和 col6 的值附加到合并的数据框中。所以理想的输出是:

merged_df:

     col1    col2   col3   col4   col5   col6
 0  Apple   store1    1      3     123    50
 1  Tree    store2    1      3     451    32 ...

当我尝试合并时,我在合并的数据帧上的 col5 和 col6 上返回了 NaN 值。请问有什么想法吗?

谢谢

【问题讨论】:

    标签: python pandas dataframe merge


    【解决方案1】:

    这是一个更复杂的例子,它有多个连接键。只有出现在左右两边的键才存在(交集),因为默认情况下 how='inner'。

    来自熊猫文档:

    结果 = pd.merge(left, right, on=['key1', 'key2'])

    result = pd.merge(def1, df2, on=['col1','col2','col3','col4'])
    

    【讨论】:

      【解决方案2】:

      你需要,

      pd.merge(df1,df2,on=['col1','col2','col3','col4'])
      [out]
      #col1   col2    col3    col4    col5    col6
      #Apple  store1  1       3       123     50
      #Tree   store2  1       3       451     32
      

      【讨论】:

        【解决方案3】:

        你想要一个内部合并。默认情况下,通用列将用于合并:

        res = df1.merge(df2, how='inner')
        
        print(res)
        
            col1    col2  col3  col4  col5  col6
        0  Apple  store1     1     3   123    50
        1   Tree  store2     1     3   451    32
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-13
          • 1970-01-01
          • 1970-01-01
          • 2020-04-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-03
          相关资源
          最近更新 更多