假设我们有一个这样的 DataFrame:
samp = pd.DataFrame({'region': ['North','North','South','South','East','East','West','West'],
'store': list('ABCDEFGH'),
'num': 100,
'year':['2020','2020','2021','2021','2021','2021','2020','2021']})
region store num year
0 North A 100 2020
1 North B 100 2020
2 South C 100 2021
3 South D 100 2021
4 East E 100 2021
5 East F 100 2021
6 West G 100 2020
7 West H 100 2021
需要按行对地区数据进行分组,按列对年份进行分组。
我通过 pivot_table or 来执行此操作groupby,这给出了相同的结果。或多或少是这样的:
pd.pivot_table(samp, index='region', columns='year',values=['store','num'],
aggfunc={'store': 'count','num':'sum'})
samp.groupby(['region','year']).agg(
total_num=("num","sum"),
stores=("store", "count")).unstack()
我们以以下形式在输出中获得必要的数据:
total_num stores
year 2020 2021 2020 2021
region
East NaN 200.0 NaN 2.0
North 200.0 NaN 2.0 NaN
South NaN 200.0 NaN 2.0
West 100.0 100.0 1.0 1.0
是否可以以某种方式更改分组顺序(层次结构?)以获取这种形式的数据(即按年份对列进行分组):
2020 2021
values total_num stores total_num stores
region
East NaN NaN 200.0 2.0
North 200.0 2.0 NaN NaN
South NaN NaN 200.0 2.0
West 100.0 1.0 100.0 1.0
在 Excel 数据透视表中,只需轻轻移动鼠标即可完成此操作,但在这里我找不到以这种形式显示数据的方法。swaplevel基本上不会改变任何东西。
这可以以某种方式完成吗?
使用DataFrame.swaplevel()和DataFrame.sort_index():
结果: