了解大Pandas中的群比

2024-04-25 08:50:43 发布

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

我希望在一个数据帧被分组后,得到其中一些值的总和。你知道吗

一些示例数据:

Race          officeID   CandidateId  total_votes   precinct
Mayor         10         705            20           Bell
Mayor         10         805            30           Bell
Treasurer     12         505            10           Bell
Treasurer     12         506            40           Bell
Treasurer     12         507            30           Bell
Mayor         10         705            50           Park
Mayor         10         805            10           Park
Treasurer     12         505            5            Park
Treasurer     12         506            13           Park
Treasurer     12         507            16           Park

为了得到每个候选人的总票数,我可以:

cand_votes = df.groupby('CandidateId').sum().total_votes
print cand_votes

CandidateId
505    15
506    53
507    46
705    70
805    40

要获得每个办公室的总票数:

total_votes = df.groupby('officeID').sum().total_votes
print total_votes

officeID
10    110
12    114

但如果我想知道每个候选人的得票率呢?我需要对每个数据对象应用某种函数吗?理想情况下,我希望最终的数据对象看起来像:

officeID    CandidateID    total_votes    vote_pct
10          705            70             .6363
10          805            40             .37

Tags: 数据parkdftotalsumgroupbyvotes候选人
1条回答
网友
1楼 · 发布于 2024-04-25 08:50:43

首先,创建一个包含候选人和办公室投票的框架。你知道吗

gb = df.groupby(['officeID','CandidateId'], as_index=False)['total_votes'].sum()

然后,您可以按office进行聚合,并使用一个转换(像索引数据一样返回)来计算office的百分比。你知道吗

gb['vote_pct'] = gb['total_votes'] / gb.groupby('officeID')['total_votes'].transform('sum')


In [146]: gb
Out[146]: 
   officeID  CandidateId  total_votes  vote_pct
0        10          705           70  0.636364
1        10          805           40  0.363636
2        12          505           15  0.131579
3        12          506           53  0.464912
4        12          507           46  0.403509

相关问题 更多 >

    热门问题