擅长:python、mysql、java
<p>使用<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html#pandas.DataFrame.melt" rel="nofollow noreferrer">^{<cd1>}</a>+<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer">^{<cd2>}</a>和<code>expand=True</code>。要创建<code>cat</code>列,可以使用<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer">^{<cd5>}</a>:</p>
<pre><code>new_df=df.melt(var_name='u_i',value_name='mouse')
new_df['cat']=new_df.groupby('u_i').cumcount()
new_df[['u','i']]=new_df['u_i'].str.split('_',expand=True)
new_df=new_df.drop('u_i',axis=1).reindex(columns=['cat','u','i','mouse'])
print(new_df)
cat u i mouse
0 0 1 1 0.049400
1 1 1 1 -0.169837
2 2 1 1 -0.192915
3 0 1 2 0.063812
4 1 1 2 0.093606
5 2 1 2 0.001477
6 0 1 3 0.097736
7 1 1 3 0.043157
8 2 1 3 0.077699
</code></pre>