Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I would like to merge two data frames, and keep the index from the first frame as the index on the merged dataset. However, when I do the merge, the resulting DataFrame has integer index. How can I specify that I want to keep the index from the left data frame?

In [441]: a=DataFrame(data={"col1": [1,2,3], 'to_merge_on' : [1,3,4]}, index=["a","b","c"])

In [442]: b=DataFrame(data={"col2": [1,2,3], 'to_merge_on' : [1,3,5]})
In [443]: a
Out[443]: 
   col1  to_merge_on
a     1            1
b     2            3
c     3            4

In [444]: b
Out[444]: 
   col2  to_merge_on
0     1            1
1     2            3
2     3            5


In [445]: a.merge(b, how="left")
Out[445]: 
   col1  to_merge_on  col2
0     1            1     1
1     2            3     2
2     3            4   NaN

In [446]: _.index
Out[447]: Int64Index([0, 1, 2])

EDIT: Switched to example code that can be easily reproduced

share|improve this question

1 Answer 1

up vote 15 down vote accepted
In [5]: a.reset_index().merge(b, how="left").set_index('index')
Out[5]:
       col1  to_merge_on  col2
index
a         1            1     1
b         2            3     2
c         3            4   NaN
share|improve this answer
    
Very clever. a.merge(b, how="left").set_index(a.index) also works, but it seems less robust (since the first part of it loses the index values to a before it resets them.) –  DanB Aug 16 '12 at 18:01
1  
For this particular case, those are equivalent. But for many merge operations, the resulting frame has not the same number of rows than of the original a frame. reset_index moves the index to a regular column and set_index from this column after merge also takes care when rows of a are duplicated/removed due to the merge operation. –  Wouter Overmeire Aug 16 '12 at 19:35
    
I didn't know why my solution would break down, but I figured it would. The reset_index() and then set_index() solution makes a lot of sense. Thanks. –  DanB Aug 17 '12 at 4:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.