将两个数据框合并在一起时对齐数据(Pandas,Python 3)

时间:2014-09-29 18:13:56

标签: python-3.x pandas

我有一个名为DF1的DF:

 Words      Type    Score
 The Man    Big       7
 The Man    Small     8
 The Man    Medium    10    

第二个名为DF2的DF:

 Words      Type    Score
 The Man    Big       10
 The Man    Small     12
 The Man    Medium    11

我想要做的是合并这两个DF并将它们对齐:

 Words      Type    Score    Type1     Score1  
 The Man    Big       7       Big       10
 The Man    Small     8       Small     12
 The Man    Medium    10      Medium    11

我正在尝试的是:

freq = pd.merge(DF1, DF2, how='outer', on='Words',suffixes=('', '1'))

但这是从该代码看起来的输出:

  Words      Type    Score    Type1     Score1  
 The Man     Big       7      Big       10
 The Man     Big       7      Small     12
 The Man     Big       7      Medium    21
 The Man     Small     8      Big       10
 The Man     Small     8      Small     12
 The Man     Small     8      Medium    21
 The Man     Medium    10     Big       10
 The Man     Medium    10     Small     12
 The Man     Medium    10     Medium    21

如何对齐数据以适合我想要的输出?

1 个答案:

答案 0 :(得分:2)

合并WordsType

In [63]: pd.merge(df1, df2, on=['Words', 'Type'], suffixes=('', '1'))
Out[63]: 
  Words    Type  Score  Score1
0   Man     Big      7      10
1   Man   Small      8      12
2   Man  Medium     10      11