我正在寻找一种优雅的方法,将一个DataFrame中的所有行追加到另一个DataFrame中(两个DataFrame具有相同的索引和列结构),但在出现相同索引值的情况下,使用第二个数据框中的行。
例如,如果我从以下数据开始:
df1:
A B
date
'2015-10-01' 'A1' 'B1'
'2015-10-02' 'A2' 'B2'
'2015-10-03' 'A3' 'B3'
df2:
date A B
'2015-10-02' 'a1' 'b1'
'2015-10-03' 'a2' 'b2'
'2015-10-04' 'a3' 'b3'
我希望你能把结果翻译成:
A B
date
'2015-10-01' 'A1' 'B1'
'2015-10-02' 'a1' 'b1'
'2015-10-03' 'a2' 'b2'
'2015-10-04' 'a3' 'b3'
这类似于某些SQL系统中所谓的"upsert",即将更新和插入组合起来。每一行数据从df2
中获取,如果行键已经存在于df1
中,则用其更新现有行。如果行键在df1
中不存在,则将其插入到df1
的末尾。我得出了以下结论:
pd.concat([df1, df2]) # concat the two DataFrames
.reset_index() # turn 'date' into a regular column
.groupby('date') # group rows by values in the 'date' column
.tail(1) # take the last row in each group
.set_index('date') # restore 'date' as the index
这种方法似乎可行,但它依赖于每个groupby组中的行顺序始终与原始DataFrame相同,我没有检查过,并且看起来过于复杂。
有没有更简单直接的解决方案?
pd.concat([df1[~df1.index.isin(df2.index)], df2])
- chrisb