代码之家  ›  专栏  ›  技术社区  ›  Alexander Engelhardt

如何在数据框中添加*或*更新列?

  •  1
  • Alexander Engelhardt  · 技术社区  · 6 年前

    我有一个现有的DataFrame和一个方法,该方法计算要添加到该DataFrame的一些列。我目前使用 pd.concat([left, right], axis=1) . 但是,当我第二次调用这个方法时,它会再次添加列(使用相同的名称)。

    left right

    left = pd.DataFrame({'one': [1, 2, 3], 'two': [2, 3, 4]})
    print(left)
    
       one  two
    0    1    2
    1    2    3
    2    3    4
    
    right = pd.DataFrame({'one': [22, 22, 22], 'NEW': [33, 33, 33]})
    print(right)
    
       one  NEW
    0   22   33
    1   22   33
    2   22   33
    

    我在找一个 foo 方法,其结果如下:

    left = left.foo(right)  # or foo(left, right)
    print(left)
    
       one  two  NEW
    0   22    2   33
    1   22    3   33
    2   22    4   33
    

    重要的是,如果我打电话 left.foo(right)

    pd.join 当列已存在时引发错误, pd.concat 不会覆盖现有列, pd.update 只覆盖现有列,但不添加新列。


    :结合以下两个答案,对我有效的解决方案是:

    result = left.\
            drop(left.columns.intersection(right.columns), axis=1).\
            join(right)
    
    2 回复  |  直到 6 年前
        1
  •  3
  •   Space Impact    6 年前

    intersection drop merge 在…上 index :

    left = left.drop(left.columns.intersection(right.columns),1).merge(right, left_index=True, right_index=True)
    
    print(left)
       two  one  NEW
    0    2   22   33
    1    3   22   33
    2    4   22   33
    
        2
  •  1
  •   jezrael    6 年前

    left = pd.concat([left, right[right.columns.difference(left.columns)]], axis=1)
    
    left = pd.concat([left, right[right.columns.difference(left.columns)]], axis=1)
    print (left)
    2   22   33
       one  two  NEW
    0    1    2   33
    1    2    3   33
    2    3    4   33