两列的Groupby合计百分比



我有一个DataFrame:

df = pd.DataFrame({
'Product': ['AA', 'AA', 'AA', 'AA', 'BB', 'BB', 'BB', 'BB'],
'Type': ['AC', 'AC', 'AD', 'AD', 'BC', 'BC', 'BD', 'BD'],
'Sales': [ 200, 100, 400, 100, 300, 100, 200, 500], 
'Qty': [ 5, 3, 3, 6, 4, 7, 4, 1]})

我想试着用";产品";以及";类型";对于两者";销售;以及";数量;。我可以得到";销售;以及";数量;分别地但我想知道是否有办法为这两个专栏做到这一点。

要获得一列的总百分比,代码为:

df['Sales'] = df['Sales'].astype(float)
df['Qty'] = df['Qty'].astype(float)
df = df[['Product', 'Type', 'Sales']]
df = df.groupby(['Product', 'Type']).agg({'Sales': 'sum'})
pcts = df.groupby(level= [0]).apply(lambda x: 100 * x / float(x.sum()))

有没有一种方法可以一次为两列实现这一点?

您可以链接groupby:

pct = lambda x: 100 * x / x.sum()
out = df.groupby(['Product', 'Type']).sum().groupby('Product').apply(pct)
print(out)
# Output
Sales        Qty
Product Type                      
AA      AC    37.500000  47.058824
AD    62.500000  52.941176
BB      BC    36.363636  68.750000
BD    63.636364  31.250000

您可以groupby"产品";以及";类型";得到每组的总数。然后CCD_ 3";产品";(其为电平=0(,并且变换sum;然后用它除以上一步的总和:

sm = df.groupby(['Product','Type']).sum()
out = sm / sm.groupby(level=0).transform('sum') * 100

输出:

Sales        Qty
Product Type                      
AA      AC    37.500000  47.058824
AD    62.500000  52.941176
BB      BC    36.363636  68.750000
BD    63.636364  31.250000

一个选项是从各个groupbys中获取值并进行除法:

numerator = df.groupby(["Product", "Type"]).sum()
denominator = df.groupby("Product").sum()
numerator.div(denominator, level = 0, axis = 'index') * 100
Sales        Qty
Product Type                      
AA      AC    37.500000  47.058824
AD    62.500000  52.941176
BB      BC    36.363636  68.750000
BD    63.636364  31.250000

最新更新