I have a table df:
class teacher January February
0 A Mary 4 3
1 B Ann 5 7
2 C Kevin 6 8
code:
import pandas as pd
df = pd.DataFrame( {'class':['A', 'B', 'C'],
'teacher':['Mary', 'Ann', 'Kevin'],
'January':['4', '5', '6'],
'February':['3', '7', '8']
} )
I need to pivot month columns to rows as new_df:
month class teacher count
0 January A Mary 4
1 January B Ann 5
2 January C Kevin 6
3 February A Mary 3
4 February B Ann 7
5 February C Kevin 8
And the month columns might grow in the future like this, so I need to pivot all of the month to new_df:
df in future:
class teacher January February March
0 A Mary 4 3 4
1 B Ann 5 7 6
2 C Kevin 6 8 4
Not really sure how to convert df to new_df by pivot. Do I need to swap columns and rows first?
(
df.set_index(['class', 'teacher'])
.stack()
.rename_axis(['class', 'teacher', 'month'])
.rename('count')
.reset_index()
)
Or:
df.melt(id_vars=['class', 'teacher'], var_name='month', value_name='count')
class teacher month count
0 A Mary January 4
1 A Mary February 3
2 B Ann January 5
3 B Ann February 7
4 C Kevin January 6
5 C Kevin February 8