回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我想问一个关于在pandas中合并多索引数据帧的问题,下面是一个假设的场景:</p>
<pre><code>arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index1 = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
index2 = pd.MultiIndex.from_tuples(tuples, names=['third', 'fourth'])
s1 = pd.DataFrame(np.random.randn(8), index=index1, columns=['s1'])
s2 = pd.DataFrame(np.random.randn(8), index=index2, columns=['s2'])
</code></pre>
<p>那么要么</p>
<pre><code>s1.merge(s2, how='left', left_index=True, right_index=True)
</code></pre>
<p>或者</p>
<pre><code>s1.merge(s2, how='left', left_on=['first', 'second'], right_on=['third', 'fourth'])
</code></pre>
<p>会导致错误。</p>
<p>是否必须对s1/s2执行reset_index()才能使此工作?</p>
<p>谢谢</p>