回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我有一个timeseries数据帧,类似于:</p>
<pre><code>ts = pd.DataFrame([['Jan 2000','WidgetCo',0.5, 2], ['Jan 2000','GadgetCo',0.3, 3], ['Jan 2000','SnazzyCo',0.2, 4],
['Feb 2000','WidgetCo',0.4, 2], ['Feb 2000','GadgetCo',0.5, 2.5], ['Feb 2000','SnazzyCo',0.1, 4],
], columns=['month','company','share','price'])
</code></pre>
<p>看起来像:</p>
^{pr2}$
<p>我可以这样旋转桌子:</p>
<pre><code>pd.pivot_table(ts,index='month', columns='company')
</code></pre>
<p>这让我:</p>
<pre><code> share price
company GadgetCo SnazzyCo WidgetCo GadgetCo SnazzyCo WidgetCo
month
Feb 2000 0.5 0.1 0.4 2.5 4 2
Jan 2000 0.3 0.2 0.5 3.0 4 2
</code></pre>
<p>这就是我想要的,只是我需要折叠<code>MultiIndex</code>,以便<code>company</code>用作{<cd3>}和{<cd4>}的前缀,如下所示:</p>
<pre><code> WidgetCo_share WidgetCo_price GadgetCo_share GadgetCo_price ...
month
Jan 2000 0.5 2 0.3 3.0
Feb 2000 0.4 2 0.5 2.5
</code></pre>
<p>我设计了一个函数来实现这一点,但这似乎是一个糟糕的解决方案:</p>
<pre><code>def pivot_table_to_flat(df, column, index):
res = df.set_index(index)
cols = res.drop(column, axis=1).columns.values
resulting_cols = []
for prefix in res[column].unique():
for col in cols:
new_col_name = prefix + '_' + col
res[new_col_name] = res[res[column] == prefix][col]
resulting_cols.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(new_col_name)
return res[resulting_cols]
pivot_table_to_flat(ts, index='month', column='company')
</code></pre>
<p>与<code>MultiIndex</code>相比,实现带有前缀的列的pivot的更好方法是什么?在</p>