代码之家  ›  专栏  ›  技术社区  ›  Mike T

从合并结果中指定值

  •  0
  • Mike T  · 技术社区  · 7 年前

    import pandas as pd
    
    sup = pd.DataFrame({'row': [0, 0, 0, 1, 1, 1, 2, 2],
                        'col': [0, 1, 2, 0, 1, 2, 1, 2], 'val': 1.3})
    #    col  row  val
    # 0    0    0  1.3
    # 1    1    0  1.3
    # 2    2    0  1.3
    # 3    0    1  1.3
    # 4    1    1  1.3
    # 5    2    1  1.3
    # 6    1    2  1.3
    # 7    2    2  1.3
    
    sub = pd.DataFrame({'Row': [2, 0, 1], 'Column': [2, 1, 0], 'Value': [1.1, 4.4, 2.4]})
    #    Column  Row  Value
    # 0       2    2    1.1
    # 1       1    0    4.4
    # 2       0    1    2.4
    

    我知道我能有效地 merge

    sup.merge(sub, left_on=['row', 'col'], right_on=['Row', 'Column'])
    #    col  row  val  Column  Row  Value
    # 0    1    0  1.3       1    0    4.4
    # 1    0    1  1.3       0    1    2.4
    # 2    2    2  1.3       2    2    1.1
    

    但是我如何覆盖中的值呢 sup['val'] 与来自 sub['Value'] ? 在我的现实世界中, sup sub 只有1k行。

    本例中的预期结果为:

    #    col  row  val
    # 0    0    0  1.3
    # 1    1    0  4.4
    # 2    2    0  1.3
    # 3    0    1  2.4
    # 4    1    1  1.3
    # 5    2    1  1.3
    # 6    1    2  1.3
    # 7    2    2  1.1
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Space Impact    7 年前

    使用 set_index 并使用 loc reset_index

    sub.rename(columns={'Row':'row', 'Column':'col', 'Value':'val'}, inplace=True)
    #alternative sub.columns = sup.columns
    sub.set_index(['row','col'], inplace=True)
    sup.set_index(['row','col'], inplace=True)
    sup.loc[sub.index,:] = sub['val']
    sup.reset_index(inplace=True)
    
    print(sup)
       row  col  val
    0    0    0  1.3
    1    0    1  4.4
    2    0    2  1.3
    3    1    0  2.4
    4    1    1  1.3
    5    1    2  1.3
    6    2    1  1.3
    7    2    2  1.1