擅长:python、mysql、java
<p>使用<code>pivot</code>和<code>stack</code>:</p>
<pre><code>(df.pivot_table(index=['Year','Month', 'Project'],
columns=['Account'], values='Value'
)
.assign(Cost=lambda x: x['Revenue']-x['Profit'])
.stack().reset_index(name='Value')
)
</code></pre>
<p>输出:</p>
<pre><code> Year Month Project Account Value
0 2020 Jan abc Profit 10
1 2020 Jan abc Revenue 100
2 2020 Jan abc Cost 90
3 2020 Jan xyz Profit 20
4 2020 Jan xyz Revenue 350
5 2020 Jan xyz Cost 330
</code></pre>