5

I have such dataframe:

import pandas as pd
data = [
        [1, 'A', 10], [1, 'B', 20], [1, 'C', 30],
        [2, 'A', 30], [2, 'B', 20], [2, 'C', 10],
        [3, 'A', 20], [3, 'B', 40], [3, 'C', 20]
       ]

df = pd.DataFrame(data, columns = ['Day', 'Company', 'Profit']) 
df 

enter image description here

I would like to transform this table such that:

  • each unique company name becomes a new column
  • remaining data is grouped by day

How can I transform the data frame to the new data frame like this?

enter image description here

Joe Rakhimov
  • 4,713
  • 9
  • 51
  • 109

2 Answers2

11

Try using a pivot table:

df_out = pd.pivot(df, index='Day', columns="Company", values="Profit").reset_index()
braml1
  • 584
  • 3
  • 13
4

You can use pivot_table:

df_pivot = df.pivot_table(index='Day', columns='Company', values='Profit')

Output:

Company   A   B   C
Day                
1        10  20  30
2        30  20  10
3        20  40  20
talatccan
  • 743
  • 5
  • 19