擅长:python、mysql、java
<p>您需要的是函数<code>pandas.DataFrame.pivot_table</code>。文档在这里<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html" rel="nofollow noreferrer">pandas/pivot_table</a>。你知道吗</p>
<p>这段代码解决了您的示例(而不是我使用的多索引列表)</p>
<pre><code>import pandas as pd
df = pd.DataFrame([
('AAA','UK','A1',2000000),
('AAA','CH','B2',4000000),
('BBB','UK','A1',7000000),
('CCC','DE','C3',5000000),
('BBB','IT','A1',10000000),
('EEE','UK','D4',11000000),
('EEE','CH','D4',3000000),
('EEE','CH','D4',6000000),
('AAA','CH','B2',8000000)],
columns=['brand', 'country', 'id', 'holding'])
df.pivot_table(values='holding',index=['id','country','brand'])
</code></pre>
<p>结果是
<a href="https://i.stack.imgur.com/vYlRo.png" rel="nofollow noreferrer">resulting dataframe</a></p>