pos*_*ist 4 python dataframe pandas pandas-groupby
我有一个数据框:
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]})
Run Code Online (Sandbox Code Playgroud)
我想尝试获取“销售”和“数量”的“产品”和“类型”的总数百分比。我可以分别获取“销售额”和“数量”占总数的百分比。但我想知道是否有办法对两个专栏都这样做。
要获取一列的总计百分比,代码为:
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()))
Run Code Online (Sandbox Code Playgroud)
有没有办法一次性获得两个列的这个?
您可以链接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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4167 次 |
| 最近记录: |