【问题标题】:append row values from one df to another if no duplicates in pandas如果 pandas 中没有重复项,则将行值从一个 df 附加到另一个
【发布时间】:2021-04-03 09:25:25
【问题描述】:

我有这两个 dfs


df1 = pd.DataFrame({'pupil': ["sarah", "john", "fred"],
                  'class': ["1a", "1a", "1a"]})


df2 = pd.DataFrame({'pupil_mixed': ["sarah", "john", "lex"],
                  'class': ["1a", "1c", "1a"]})


我想从 df2 中附加“pupil_mixed”列中的行值 如果值不重复,则到 df1 中的“瞳孔”列

期望的结果:

df1 = pd.DataFrame({'pupil': ["sarah", "john", "fred", 'lex'],
                  'class': ["1a", "1a", "1a", NaN]})


我使用appendloc

df1 = df1.append(df2.loc[df2['pupil_mixed'] != df1['pupil'] ])

它只是将另一列附加到具有匹配行值的df,并将不匹配的行值更改为NaN

    pupil   class   pupil_mixed
0   sarah   1a      NaN
1   john    1a      NaN
2   fred    1a      NaN
2   NaN     1a      lex




【问题讨论】:

  • 为什么 lex 的类是NaN

标签: python pandas dataframe append


【解决方案1】:

你可以使用concat + drop_duplicates:

res = pd.concat((df1, df2['pupil_mixed'].to_frame('pupil'))).drop_duplicates('pupil')

print(res)

输出

   pupil class
0  sarah    1a
1   john    1a
2   fred    1a
2    lex   NaN

作为替代方案,您可以先过滤(使用isin)然后连接:

# filter the rows in df2, rename the column pupil_mixed
filtered = df2.loc[~df2['pupil_mixed'].isin(df1['pupil'])]

# create a new single column DataFrame with the pupil column
res = pd.concat((df1, filtered['pupil_mixed'].to_frame('pupil')))

print(res)

两种解决方案都使用to_frame,带有name参数,有效地改变了的名称。

【讨论】:

    【解决方案2】:
    # distinct df1 & df2
    df1['tag'] = 1
    df2['tag'] = 2
    
    # change the column name the same
    df2.columns = df1.columns
    df1 = df1.append(df2)
    # drop_duplicates by keep df1
    df1 = df1.drop_duplicates('pupil', keep='first')
    
    # set tag == 2, class is null
    cond = df1['tag'] == 2
    df1.loc[cond, 'class'] = np.nan
    del df1['tag']
    
    print(df1)
    

    输出:

    print(df1)
    
       pupil class
    0  sarah    1a
    1   john    1a
    2   fred    1a
    3    lex   NaN
    

    【讨论】:

      【解决方案3】:

      在 df2 中重命名 pupil_mixed 后,您可以使用合并:

      df1.merge(df2["pupil_mixed"].rename("pupil"), how="outer")
      
         pupil    class
      0   sarah   1a
      1   john    1a
      2   fred    1a
      3   lex    NaN
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-05-09
        • 1970-01-01
        • 2019-06-19
        • 2020-04-05
        • 1970-01-01
        • 2022-12-15
        • 1970-01-01
        相关资源
        最近更新 更多