【问题标题】:Python Pandas: Append Dataframe To Another Dataframe Only If Column Value is UniquePython Pandas:仅当列值唯一时才将数据框附加到另一个数据框
【发布时间】:2019-01-28 21:05:41
【问题描述】:

我有两个要附加在一起的数据框。以下是样本。

df_1:

Code    Title
103     general checks 
107     limits
421     horseshoe
319     scheduled 
501     zonal 

df_2

Code    Title
103     hello 
108     lucky eight 
421     little toe 
319     scheduled cat
503     new item 

仅当 df_2 中的代码号在 df_1 中不存在时,我才想将 df_2 附加到 df_1。

下面是我想要的数据框:

Code    Title
103     general checks 
107     limits
421     horseshoe
319     scheduled 
501     zonal 
108     lucky eight 
503     new item

我已经通过 Google 和 Stackoverflow 进行了搜索,但在这个特定案例中找不到任何内容。

【问题讨论】:

    标签: python pandas append conditional


    【解决方案1】:

    append过滤后的数据框

    df3 = df2.loc[~df2.Code.isin(df.Code)]
    df.append(df3)
    
        Code    Title
    0   103 general checks
    1   107 limits
    2   421 horseshoe
    3   319 scheduled
    4   501 zonal
    1   108 lucky eight
    4   503 new item
    

    请注意,您最终可能会得到重复的索引,这可能会导致问题。为避免这种情况,您可以.reset_index(drop=True) 获取没有重复索引的新 df。

    df.append(df3).reset_index(drop=True)
    
        Code    Title
    0   103 general checks
    1   107 limits
    2   421 horseshoe
    3   319 scheduled
    4   501 zonal
    5   108 lucky eight
    6   503 new item
    

    【讨论】:

      【解决方案2】:

      您可以先concat,然后再drop_duplicates。假设在每个数据帧内 Code 是唯一的。

      res = pd.concat([df1, df2]).drop_duplicates('Code')
      
      print(res)
      
         Code           Title
      0   103  general_checks
      1   107          limits
      2   421       horseshoe
      3   319       scheduled
      4   501           zonal
      1   108     lucky_eight
      4   503        new_item
      

      【讨论】:

        【解决方案3】:

        类似于 concat(),你也可以使用 merge:

        df3 = pd.merge(df_1, df_2, how='outer').drop_duplicates('Code')
        
            Code    Title
        0   103 general checks
        1   107 limits
        2   421 horseshoe
        3   319 scheduled
        4   501 zonal
        6   108 lucky eight
        9   503 new item  
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-10
          • 1970-01-01
          • 2019-09-28
          相关资源
          最近更新 更多