Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have the 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

I like to transform 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 any way to do this in Python? I have read the documentation for pandas.DataFrame.groupby and pandas.DataFrame.transpose, but still, I don't see how it can be used to accomplish the above transformation.

1 Answer

0 votes
by (36.8k points)

The 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

Want to be a Data Science expert? Come and join this Data Science Courses

 

Browse Categories

...