我正在尝试创建一个具有多列的数据透视表;我不知道如何更好地解释这个问题,但以下是所需的输出, Dataframe 设置,和代码,我已经尝试了。
**所需输出:x1c 0d1x
** Dataframe 设置:
data = {
'WholesalerID': {0: 121, 1: 121, 2: 42, 3: 42, 4: 54, 5: 43, 6: 432, 7: 4245, 8: 4245, 9: 4245, 10: 457},
'Brand': {0: 'Vans', 1: 'Nike', 2: 'Nike', 3: 'Vans',4: 'Vans', 5: 'Nike', 6: 'Puma', 7: 'Vans', 8: 'Nike', 9: 'Puma', 10: 'Converse'},
'Shop 1': {0: 'Yes', 1: 'No', 2: 'Yes', 3: 'Maybe', 4: 'Yes', 5: 'No', 6: 'Yes', 7: 'Yes', 8: 'Maybe', 9: 'Maybe', 10: 'No'},
'Shop 2': {0: 'No', 1: 'Yes', 2: 'Maybe', 3: 'Maybe', 4: 'Yes', 5: 'No', 6: 'No', 7: 'No', 8: 'Maybe', 9: 'Yes', 10: 'Yes'}
}
df = pd.DataFrame.from_dict(data)
旋转尝试:
df = df.assign(count = 1)
pivoted_df = pd.pivot_table(df,
index = ['Brand'],
columns = ['Shop 1', 'Shop 2'],
values = ['count'],
aggfunc = {'count': 'count'},
fill_value = 0,
margins = True,
margins_name = 'Total'
)
1条答案
按热度按时间hivapdat1#
使用
DataFrame.melt
进行逆透视,然后将列value
转换为Categorical
以正确排序最终MultiIndex
,按crosstab
整形,按列的第一级添加小计,并使用添加级Total
追加到原始列: