<p><strong>使用:</strong></p>
<pre><code>m = df['type'].eq('price') & df['asset'].isin(['x', 'y'])
d = df[m].pivot('date', 'asset', 'value').astype(float)
d = pd.concat(
[df, d['x'].sub(d['y']).reset_index(name='value').assign(
asset='x_min_y', type='pricediff')],
ignore_index=True)
</code></pre>
<hr/>
<p><strong>详细信息:</strong></p>
<p>创建一个布尔掩码<code>m</code>以过滤<code>type</code>为<code>price</code>且<code>asset</code>为<code>x, y</code>的行,并使用<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer">^{<cd6>}</a>重新塑造数据帧:</p>
<pre><code>print(d) # pivoted dataframe
asset x y
date
2020-01-01 1.5 1.0
2020-01-02 1.6 1.2
</code></pre>
<p>使用<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.sub.html" rel="nofollow noreferrer">^{<cd7>}</a>从数据透视帧中的<code>y</code>中减去列<code>x</code>,并分配列<code>asset</code>和<code>type</code>,然后使用<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer">^{<cd12>}</a>将该数据透视帧与原始数据帧<code>df</code>连接</p>
<pre><code>print(d)
date asset type value
0 2020-01-01 x price 1.5
1 2020-01-01 x spread 0.01
2 2020-01-02 x price 1.6
3 2020-01-02 x spread 0.01
4 2020-01-01 y price 1
5 2020-01-01 y spread 0.08
6 2020-01-02 y price 1.2
7 2020-01-02 y spread 0.09
8 2020-01-01 x_min_y pricediff 0.5
9 2020-01-02 x_min_y pricediff 0.4
</code></pre>