0

I want to convert the data given here from:

original_data

to this:

transformed_data

where the numbers are Sales against each company. How can I do this with Python?

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
  • Does this answer your question? [How can I pivot a dataframe?](https://stackoverflow.com/questions/47152691/how-can-i-pivot-a-dataframe) – ThePyGuy Aug 20 '21 at 20:29

2 Answers2

1

pandas' groupby function is your friend. You can use it to group by month and company, and then rearrange to grouping by company (which appears as index) into columns:

df.groupby(['Month', 'Company'])['Sales'].sum().unstack()

After the groupby(['Month', 'Company'])['Sales'].sum() you have companies as indices, therefore the use of unstack() to change them in to columns.

Roim
  • 2,986
  • 2
  • 10
  • 25
1

You can use DataFrame.pivot

The pivot call will reshape the dataframe from rows to columns and fillna(0) will replace the empty cells with zero, finally reset_index will get rid of hierarchical column

df.pivot(index='Month', columns='Company', values='Sales').fillna(0).reset_index()

OUTPUT:

Company  Month  Apple    HP
0            1    8.0   0.0
1            2    8.0   0.0
2            3   14.0   0.0
3            4    3.0   0.0
4            5    4.0  10.0
5            6    3.0   9.0
6            7   14.0   9.0
7            8    0.0  10.0
8            9    0.0   3.0
9           10    0.0   4.0

PS: It is recommended to add your data as text while asking the question, we can not copy the contents from image.

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45