2017-03-04 29 views
1

我正在尝试做一些我认为应该是单行程式的东西,但我正在努力做正确的事。熊猫:将小型数据框合并为大型,用小型覆盖

我有一个很大的数据框,我们将其称为lg,以及一个小数据框,我们将其称为sm。每个数据帧有一个start和一个end列,以及多个其他列,它们在两个数据帧(为了简单起见,我们将调用所有这些列type)之间是相同的。有时候,sm将具有相同startendlg,如果是这样的话,我想smtype覆盖lgtype

这里的设置:

lg = pd.DataFrame({'start':[1,2,3,4], 'end':[5,6,7,8], 'type':['a','b','c','d']}) 
sm = pd.DataFrame({'start':[9,2,3], 'end':[10,6,11], 'type':['e','f','g']}) 

...请注意,只有匹配['start','end']组合是['2','6']

我想要的输出:

start end type 
0  1 5 a 
1  2 6 f # where sm['type'] overwrites lg['type'] because of matching ['start','end'] 
2  3 7 c 
3  3 11 g # where there is no overwrite because 'end' does not match 
4  4 8 d 
5  9 10 e # where this row is added from sm 

我试过的.merge()多个版本,merge_ordered()等,但无济于事。实际上,我已经将它与merge_ordered()drop_duplicates()配合使用,仅仅意识到它只是删除了字母表中较早的副本,而不是因为它来自sm

回答

1

你可以尝试设置startend列的索引,然后使用combine_first

sm.set_index(['start', 'end']).combine_first(lg.set_index(['start', 'end'])).reset_index() 

enter image description here

+0

知道我失去了一些东西简单。谢谢! – pshep123

+0

不客气,很高兴它适合你。 – Psidom