Melt & pivot

How to rotate tables 🚦 🚥 with pandas
Pandas
Python
Author

Johannes Tomasoni

Published

November 11, 2022

date fruit amount quality
0 2022-09-01 apple (red) 4 3
1 2022-09-01 grape (red) 5 1
2 2022-09-01 grape (white) 6 3
3 2022-09-03 grape (red) 6 2
4 2022-09-03 grape (white) 4 2
5 2022-09-04 apple (red) 2 1
6 2022-09-04 grape (white) 9 1
7 2022-09-05 apple (red) 5 1
8 2022-09-05 grape (red) 5 2
9 2022-09-05 grape (white) 8 3

Pivot

data_pv = data.pivot(index='date', columns='fruit', 
                     values=['amount','quality']).reset_index()
data_pv
date amount quality
fruit apple (red) grape (red) grape (white) apple (red) grape (red) grape (white)
0 2022-09-01 4.0 5.0 6.0 3.0 1.0 3.0
1 2022-09-03 NaN 6.0 4.0 NaN 2.0 2.0
2 2022-09-04 2.0 NaN 9.0 1.0 NaN 1.0
3 2022-09-05 5.0 5.0 8.0 1.0 2.0 3.0

Melt (Unpivot)

data_pv.columns = ['date', 'apple (red)_amt', 'grape (red)_amt',
                   'grape (white)_amt','apple (red)_qlt',
                   'grape (red)_qlt','grape (white)_qlt']
data_pv.melt(id_vars='date', value_vars=['apple (red)_amt', 
                                         'grape (red)_amt',
                                         'grape (white)_amt'])
date variable value
0 2022-09-01 apple (red)_amt 4.0
1 2022-09-03 apple (red)_amt NaN
2 2022-09-04 apple (red)_amt 2.0
3 2022-09-05 apple (red)_amt 5.0
4 2022-09-01 grape (red)_amt 5.0
5 2022-09-03 grape (red)_amt 6.0
6 2022-09-04 grape (red)_amt NaN
7 2022-09-05 grape (red)_amt 5.0
8 2022-09-01 grape (white)_amt 6.0
9 2022-09-03 grape (white)_amt 4.0
10 2022-09-04 grape (white)_amt 9.0
11 2022-09-05 grape (white)_amt 8.0