擅长:python、mysql、java
<p>让我们使用<code>pd.wide_to_long</code>来处理这种同时熔化的情况</p>
<p>首先,我们需要重命名列标题,为列创建一种格式,使其具有公共“存根”</p>
<pre><code># Here we are adding '1' on the end of columns without the number 2 on thend
df = df.rename(columns=lambda x: x+'1' if x[-1] != '2' else x)
# Now, let's reshape using pd.wide_to_long
pd.wide_to_long(df.reset_index(), ['State', 'Homicides'], 'index', 'No').reset_index(level=1, drop=True)
</code></pre>
<p>乌普图特:</p>
<pre><code> State Homicides
index
0 Cal 1.0
1 Tex 2.0
2 Tenn 3.0
3 Pen 4.0
0 Mas 5.0
1 NY 6.0
2 Chi 7.0
3 Mon 8.0
</code></pre>