对于不匹配的索引,Pandas full outer index与NaN连接

时间:2017-04-04 11:32:08

标签: python pandas join merge

尝试在这两个Pandas数据帧上进行完全外连接:

df1 = pd.DataFrame({'a': [1,2,1], 'b': [1,1,2], 'c': [1,2,3]}).set_index(['a', 'b'])
df2 = pd.DataFrame({'a': [1,2,3], 'd': [11,12,13]}).set_index(['a'])

>>> df1
     c
a b   
1 1  1
2 1  2
1 2  3

>>> df2
    d
a    
1  11
2  12
3  13

我继续合并这两个:

>>> df1.merge(df2, how='outer', left_index=True, right_index=True)

     c   d
a b       
1 1  1  11
2 1  2  12
1 2  3  11

虽然我希望在这个连接中也应该返回不匹配的索引,如下所示:

       c    d
a b       
1 1    1    11
2 1    2    12
3 NaN  NaN  13
1 2    4    11

2 个答案:

答案 0 :(得分:1)

你可以使用一个小技巧 - b级别mergebdf2 = df1.reset_index(level='b') .merge(df2, how='outer', left_index=True, right_index=True) .set_index('b', append=True) print (df2) c d a b 1 1.0 1.0 11 2.0 3.0 11 2 1.0 2.0 12 3 NaN NaN 13 public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('Families', ChoiceType::class, array( 'choices' => array( 'Monosaccharides' => 'Monosaccharides', 'Oligosaccharides ' => 'Oligosaccharides ', 'Polysaccharides' => 'Polysaccharides' ), 'placeholder' => 'Choose an option', 'required' => false )) ->add('MolecularGroups', ChoiceType::class, array( 'choices' => array( 'Monosaccharide' => 'Monosaccharide', 'Oligosaccharide' => 'Oligosaccharide', 'Cyanogenic glycoside' => 'Cyanogenic glycoside' ), 'placeholder' => 'Choose an option', 'required' => false )); } {/ 1}}:

<ul id="slide-out" class="side-nav">
      <li><a href="#!">Home</a></li>
      <li><a href="#!">Products</a></li>
      <li><a href="#!">Contact</a></li>
    </ul>
    <a href="#" data-activates="slide-out" class="button-collapse show-on-large"><i class="material-icons">menu</i></a>

答案 1 :(得分:1)

我认为这正是您所寻找的,因为这不仅仅是一个连接,而是一个MultiIndex连接。

{{1}}

它的输出相同,但在这种情况下索引是有序的。