简体   繁体   中英

merge data frames with duplicated indices

Is there any way to merge two data frames while one of them has duplicated indices such as following:

dataframe A:

     value    
 key
  a    1
  b    2
  b    3
  b    4
  c    5
  a    6

dataframe B:

       number
  key
   a     I
   b     X
   c     V

after merging, I want to have a data frame like the following:

       value      number
  key
   a     1          I
   b     2          X
   b     3          X
   b     4          X
   c     5          V
   a     6          I

Or maybe there are better ways to do it using groupby?

Use join :

>>> a = pd.DataFrame(range(1,7), index=list('abbbca'), columns=['value'])
>>> b = pd.DataFrame(['I', 'X', 'V'], index=list('abc'), columns=['number'])
>>> a.join(b)
   value number
a      1      I
a      6      I
b      2      X
b      3      X
b      4      X
c      5      V
>>> a.join(b).sort('value')
     value number
key              
a        1      I
b        2      X
b        3      X
b        4      X
c        5      V
a        6      I

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM