我有一张桌子 df:
class teacher January February
0 A Mary 4 3
1 B Ann 5 7
2 C Kevin 6 8
代码:
import pandas as pd
df = pd.DataFrame( {'class':['A', 'B', 'C'],
'teacher':['Mary', 'Ann', 'Kevin'],
'January':['4', '5', '6'],
'February':['3', '7', '8']
} )
我需要将月份列转为行作为 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
月份列将来可能会像这样增长,所以我需要将整个月份转为 new_df:
未来的df:
class teacher January February March
0 A Mary 4 3 4
1 B Ann 5 7 6
2 C Kevin 6 8 4
不太确定如何通过数据透视将 df 转换为 new_df 。我需要先交换列和行吗?
这是一种方法:
(
df.set_index(['class', 'teacher'])
.stack()
.rename_axis(['class', 'teacher', 'month'])
.rename('count')
.reset_index()
)
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