<p>对<code>MultiIndex</code>的所有列使用<code>split</code>,然后按<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html" rel="nofollow noreferrer">^{<cd3>}</a>重塑,按<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename_axis.html" rel="nofollow noreferrer">^{<cd4>}</a>更改新列名的级别,最后按<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.reset_index.html" rel="nofollow noreferrer">^{<cd5>}</a>将其转换为列:</p>
<pre><code>df.columns = df.columns.str.split('_', expand=True)
df = df.unstack().rename_axis(('u','i','cat')).reset_index(name='mouse')
print (df.head(10))
u i cat mouse
0 1 1 0 0.049400
1 1 1 1 -0.169837
2 1 1 2 -0.192915
3 1 2 0 0.063812
4 1 2 1 0.093606
5 1 2 2 0.001477
6 1 3 0 0.097736
7 1 3 1 0.043157
8 1 3 2 0.077699
9 1 4 0 -0.077222
</code></pre>
<p>您的解决方案应该首先用<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html" rel="nofollow noreferrer">^{<cd7>}</a>中的参数<code>sep</code>进行更改,然后用<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer">^{<cd8>}</a>进行另一个重塑,并进行一些数据清理:</p>
<pre><code>u_seq_stub = ['1','2',...,'9','10']
#alternative
#u_seq_stub = [str(x) for x in range(1,11)]
df = (pd.wide_to_long(df.reset_index(),
u_seq_stub,
i='index',
j='i',
sep='_')
.stack()
.reset_index(name='mouse')
.rename(columns={'index':'cat', 'level_2':'u'})
.astype({'i':int, 'u':int})
.sort_values(['u','i','cat'])
)
print (df.head(10))
cat i u mouse
0 0 1 1 0.049400
12 1 1 1 -0.169837
24 2 1 1 -0.192915
3 0 2 1 0.063812
15 1 2 1 0.093606
25 2 2 1 0.001477
5 0 3 1 0.097736
17 1 3 1 0.043157
26 2 3 1 0.077699
7 0 4 1 -0.077222
</code></pre>