【发布时间】:2015-10-07 20:11:24
【问题描述】:
我正在寻找一种优雅的方式将所有行从一个 DataFrame 附加到另一个 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 中的每一行要么(a)用于更新现有行如果行键已经存在于df1 中,则在df1 中,或者(b)如果行键不存在,则在末尾插入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 组中的行顺序始终与原始 DataFrames 相同,我没有检查过,而且看起来令人不快地令人费解。
有人对更直接的解决方案有任何想法吗?
【问题讨论】: