代码之家  ›  专栏  ›  技术社区  ›  PythonSherpa

合并数据帧,覆盖键上的值

  •  1
  • PythonSherpa  · 技术社区  · 7 年前

    如果这个问题是重复的,我很抱歉。我实在找不到这个具体案件的答案。如果键('id')也存在于第二个数据帧中,是否可以合并/联接两个数据帧,同时覆盖第一个数据帧中的值? 有点像SQL中的INSERT-ON-DUPLICATE-KEY-UPDATE命令。

    第一个数据帧“df1”:

        id      value
    0   100010  25
    1   100011  22
    2   100012  30
    

    第二个数据帧“df2”:

        id      value
    0   100012  35
    1   100013  36
    

    合并dataframes会产生新列,并保留“id”“100012”的旧数据:

    df3 =  pd.merge(df1, df2, on='id', how='outer')
    print(df3)
    
        id      value_x value_y
    0   100010  25.0    NaN
    1   100011  22.0    NaN
    2   100012  30.0    35.0
    3   100013  NaN     36.0
    

    是否可以直接从merge函数获得所需的输出?所以只更新“id”“100012”并添加新行“100013”?

        id      value
    0   100010  25
    1   100011  22
    2   100012  35
    3   100013  36
    

    我试过了 merge , join , update combine_first

    2 回复  |  直到 7 年前
        1
  •  1
  •   rafaelc    7 年前

    简单使用 pd.concat 索引不在 df2 的索引。让

    df  = df.set_index('id')
    df2 = df2.set_index('id')
    

    那么

    >>> merged = pd.concat([df[~df.index.isin(df2.index)], df2]).reset_index()
    
        id      value
    0   100010  25
    1   100011  22
    2   100012  35
    3   100013  36
    
        2
  •  2
  •   jamesj629    7 年前

    编辑:

    >>> df1=df1.set_index('id')
    >>> df2=df2.set_index('id')
    

    先使用联合收割机 df2

    >>> df2.combine_first(df1)
           value
    id
    100010    25
    100011    22
    100012    35
    100013    36
    

    >>>df1=df1.设置索引('id')
    &燃气轮机&燃气轮机&燃气轮机;df2=df2.设置索引('id')
    

    用…编一本字典 df1

    >>> d = df1.to_dict( 'index' )
    >>> d
    {'100012': {'value': '30'}, '100010': {'value': '25'}, '100011': {'value': '22'}}
    

    update()

    >>> d.update( df2.to_dict( 'index' ) )
    >>> d
    {'100012': {'value': '35'}, '100013': {'value': '36'}, '100010': {'value': '25'}, '100011': {'value': '22'}}
    

    将其转换回数据帧:

    >>> pd.DataFrame.from_dict( d, 'index' )
           value
    100010    25
    100011    22
    100012    35
    100013    36