【问题标题】:Pandas DataFrame updating Column values with other DataFramePandas DataFrame 使用其他 DataFrame 更新列值
【发布时间】:2018-06-25 21:52:35
【问题描述】:

考虑以下 DataFrame X:

Col A Col B 
1     2
3     4
5     6

数据帧 Y:

Col A Col B 
3     7
8     9

pandas 中是否存在一个内置函数,它将合并两个数据帧,使用 Col A 作为键,如果存在则更新 Col B 中的值,否则追加。这样这个函数在 X 和 Y 上的输出是

Col A Col B
1     2
3     7
5     6
8     9

我已经研究过合并、更新和追加,但它们似乎没有按照我想要的方式行事,通过索引而不是 Col A 值更新更新,合并不会覆盖,等等。谢谢!

【问题讨论】:

    标签: pandas


    【解决方案1】:

    一种方法是先concat 然后drop the duplicates

    In [11]: df = pd.concat([dfX, dfY])
    
    In [12]: df
    Out[12]:
       ColA  ColB
    0     1     2
    1     3     4
    2     5     6
    0     3     7
    1     8     9
    
    In [13]: df.drop_duplicates(cols=['ColA'], take_last=True)
    Out[13]:
       ColA  ColB
    0     1     2
    2     5     6
    0     3     7
    1     8     9
    

    注意:take_last 参数表示您正在“从 dfY 更新”。

    【讨论】:

    • 注 2:有趣的是,在 ubutbu 的(已删除)答案中,他使用了 combine_first(但发现它的速度是这种方法的两倍)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2016-02-10
    • 1970-01-01
    • 2016-09-05
    • 2020-07-23
    • 1970-01-01
    • 2017-04-15
    相关资源
    最近更新 更多