1

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,203
  • 8
  • 44
  • 101

2 Answers2

7

Try using a pivot table:

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

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
  • 717
  • 4
  • 18