擅长:python、mysql、java
<p>考虑数据帧</p>
<pre><code> C D E
A B
a 4 7.0 1.0 5.0
5 3.0 4.0 5.5
b 5 8.0 3.0 3.0
c 4 9.0 5.0 6.0
f 4 3.0 0.0 4.0
</code></pre>
<p>您可以使用<code>df.reset_index</code>drop is False,它可以根据索引级别生成列数,然后您可以在主索引转换后将其分配给主索引</p>
<pre><code>#converting index to columns
df = df1.reset_index()
# Assigning multilevel index columns to main index
df.index = df[df.columns[0]].astype(str)+' '+df[df.columns[1]].astype(str)
# dropping the indexed columns
df = df.drop(df.columns[[0,1]],axis=1)
</code></pre>
<p>输出:</p>
<pre><code> C D E
a 4 7.0 1.0 5.0
a 5 3.0 4.0 5.5
b 5 8.0 3.0 3.0
c 4 9.0 5.0 6.0
f 4 3.0 0.0 4.0
</code></pre>