我正在寻找一种优雅的方法将一个 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 组中的行顺序始终与原始 DataFrame 相同,我还没有检查过,并且看起来令人不快地复杂。
有谁有更直接的解决方案的想法吗?
一种解决方案是串联df1
有新行df2
(即索引不匹配的地方)。然后用来自的值更新值df2
.
df = pd.concat([df1, df2[~df2.index.isin(df1.index)]])
df.update(df2)
>>> df
A B
2015-10-01 A1 B1
2015-10-02 a1 b1
2015-10-03 a2 b2
2015-10-04 a3 b3
EDIT:根据@chrisb的建议,可以进一步简化如下:
pd.concat([df1[~df1.index.isin(df2.index)], df2])
谢谢克里斯!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)