简体   繁体   English

列标题(如数据透视表)

[英]Column headers like pivot table

I am trying to find out the mix of member grades that visit my stores. 我正在尝试找出访问我商店的会员等级组合。

import pandas as pd

df=pd.DataFrame({'MbrID':['M1','M2','M3','M4','M5','M6','M7']
                    ,'Store':['PAR','TPM','AMK','TPM','PAR','PAR','AMK']
                    ,'Grade':['A','A','B','A','C','A','C']})
df=df[['MbrID','Store','Grade']]
print(df)

df.groupby('Store').agg({'Grade':pd.Series.nunique})

Below is the dataframe and also the result of groupby function. 以下是数据框以及groupby函数的结果。

在此处输入图片说明

How do I produce the result like Excel Pivot table, such that the categories of Grade (A,B,C) is the column headers? 如何产生类似Excel Pivot表的结果,使成绩(A,B,C)的类别为列标题? This is assuming that I have quite a wide range of member grades. 这是假设我的会员等级范围很广。

I think you can use groupby with size and reshaping by unstack : 我认为您可以将groupbysize配合使用,并通过unstack重塑:

df1 = df.groupby(['Store','Grade'])['Grade'].size().unstack(fill_value=0)
print (df1)
Grade  A  B  C
Store         
AMK    0  1  1
PAR    2  0  1
TPM    2  0  0

Solution with crosstab : 使用crosstab解决方案:

df2 = pd.crosstab(df.Store, df.Grade)
print (df2)
Grade  A  B  C
Store         
AMK    0  1  1
PAR    2  0  1
TPM    2  0  0

and with pivot_table : 并使用pivot_table

df3 = df.pivot_table(index='Store', 
                     columns='Grade', 
                     values='MbrID', 
                     aggfunc=len,
                     fill_value=0)
print (df3)
Grade  A  B  C
Store         
AMK    0  1  1
PAR    2  0  1
TPM    2  0  0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM