user13867283
user13867283

Reputation:

Transformation of Pandas Dataframe

I have a Pandas DataFrame that looks something like:

    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

And I would like to transform it so that it looks something like:

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

Is there an efficient way to do this in Python? I have read the documentation for pandas.DataFrame.groupby and pandas.DataFrame.transpose, but I still don't see how either could be used to accomplish the above transformation.

Upvotes: 0

Views: 54

Answers (1)

Serial Lazer
Serial Lazer

Reputation: 1669

pivot-tables would suffice for your use-case:

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

Upvotes: 2

Related Questions