转换熊猫数据框

时间:2020-11-11 04:49:08

标签: python pandas dataframe

我有一个看起来像这样的Pandas DataFrame:

    Store   Month   Sales
0   1       Jan     1100
1   1       Feb     1300
2   1       Mar     1250
3   1       Apr     1500
4   2       Jan     900
5   2       Feb     950
6   2       Mar     800
7   2       Apr     900

我想对其进行转换,使其看起来像:

    Store   Jan     Feb     Mar     Apr
0   1       1100    1300    1250    1500
1   2       1900    1950    1800    900

在Python中是否有一种有效的方法?我已经阅读了pandas.DataFrame.groupbypandas.DataFrame.transpose的文档,但是仍然看不到如何使用它们来完成上述转换。

1 个答案:

答案 0 :(得分:3)

pivot-tables足以满足您的用例:

print(df.pivot_table(index='Store', columns=['Month'], values='Sales'))
       Apr   Feb   Jan   Mar
Store                        
1     1500  1300  1100  1250
2      900   950   900   800