数据:
year month is_p segment x y
2018 JAN Y de 200 500
2018 JAN N de 100 200
2018 JAN N de 500 500
2018 JAN Y de 1000 500
预期产量:
year month segment is_p x y %of allocation_x %of allocation_y
2018 JAN de N 600 700 0.333333 0.411765
Y 1200 1000 0.666667 0.588235
我尝试过的操作:我进行了分组,并对所有Y的值求和。求和后,我将y的贡献除以总和。
df_p=df.groupby([year,month,is_p,segment]).sum()
# To get the total sum for Y & N for is_p column
df_total=df.groupby([year,month,segment]).sum()
# To get the total sum per segment.
现在,我想获取x,y
相对于is_p
列的值的百分比(列- )。如果还有其他方法,请提供相同的帮助。
这是我的解决方案!首先进行['year','month','segment']
分组,然后在每个组中获得x和y的和is_p
。用总和,然后获得每个子类别的百分比
d=''' year month is_p segment x y
2018 JAN Y de 200 500
2018 JAN N de 100 200
2018 JAN N de 500 500
2018 JAN Y de 1000 500
2019 JAN Y de 200 500
2019 JAN N de 100 2000
2019 JAN N de 5000 500
2019 JAN Y de 1000 500'''
df = pd.read_csv(pd.compat.StringIO(d), sep='\s+')
def f(x):
grouped = x.groupby('is_p').agg(sum)
for c in grouped.columns:
grouped['%of allocation'+str(c)] = grouped[c]/grouped[c].sum()
return grouped
interested_cols =['x','y']
df.groupby(['year','month','segment'])[['is_p']+interested_cols].apply(f)
输出:
x y %of allocation_x %of allocation_y
year month segment is_p
2018 JAN de N 600 700 0.333333 0.411765
Y 1200 1000 0.666667 0.588235
2019 JAN de N 5100 2500 0.809524 0.714286
Y 1200 1000 0.190476 0.285714
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句