如何旋转这个 Pandas DataFrame?

How can I pivot this Pandas DataFrame?

我正在读取具有以下结构的 csv 文件:

Continent, Country, Year, GDP

所有国家都有多个年份,但有些国家可能缺少一些年份。

我的目标是将大陆和国家作为索引,并将每年的 GDP 作为列。

Continent Country 2009 2010 2011 2012 2013 2014

我试过这个:

df.pivot(index=["Continent", "Country"], columns="Year", values="GDP")

但它给了我这个错误:

ValueError: Buffer has wrong number of dimensions (expected 1, got 2)

您可以试试这个示例数据:

pd.DataFrame(columns=['Continent', 'Country', 'Year', 'GDP'],
             data=[['NA', 'US', 2014, 1234], ['NA', 'US', 2013, 2345]])

如果您使用 pivot_table 而不是 pivot,它会起作用:

In [47]: df.pivot_table(index=["Continent", "Country"], columns="Year", values="GDP")
Out[47]:
Year               2013  2014
Continent Country
NA        US       2345  1234

问题是 pivot 无法处理 index/columns 参数的列列表。唯一需要注意的是,如果一个 continent/country/year 组合有多个值,现在默认取平均值。