Home > Enterprise >  Using Pivot/melt to transform pandas data
Using Pivot/melt to transform pandas data

Time:04-12

I have dataframe like

import pandas as pd 

pd.DataFrame({'Date': ["2022-01-01","2022-01-02","2022-01-03"],
         'customer_type': ['A','A','B'],
         'process_A': [2,4,5],
         'process_B': [3,9,6]})

op
      Date         customer_type    process_A   process_B
0     2022-01-01    A               2           3
1     2022-01-02    A               4           9
2     2022-01-03    B               5           6

what I want it to transform in such a way that Date become column and dataframe look like this

  customer_type    Process  2022-01-01  2022-01-02  2022-01-03
0             A  process_A           2           4           0
1             A  process_B           3           9           0
2             B  process_A           0           0           5
3             B  process_B           0           0           6

CodePudding user response:

You can combine melt and pivot_table:

(df
 .melt(id_vars=['Date', 'customer_type'], var_name='Process')
 .pivot_table(index=['customer_type', 'Process'], columns='Date',
              values='value', fill_value=0)
 .reset_index()
 .rename_axis(columns=None)
)

output:

  customer_type    Process  2022-01-01  2022-01-02  2022-01-03
0             A  process_A           2           4           0
1             A  process_B           3           9           0
2             B  process_A           0           0           5
3             B  process_B           0           0           6
  • Related