划分数据帧

2024-03-29 00:40:39 发布

您现在位置:Python中文网/ 问答频道 /正文

数据:

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

我尝试过的: 我做了groupby,取所有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列的百分比。 如果有其他方法,请帮忙。你知道吗


Tags: ofthetodfgetissegmentde
1条回答
网友
1楼 · 发布于 2024-03-29 00:40:39

这是我的解决办法! 首先在['year','month','segment']上执行groupby,然后在每个组内得到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

相关问题 更多 >