2014-10-01 100 views
1

我期待在数据框被分组之后得到某些数据框中某些值的总和。了解pandas中的groupby

一些样本数据:

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 

要获得的选票为每名候选人的总和,我可以这样做:

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

officeID 
10 110 
12 114 

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

CandidateId 
505 15 
506 53 
507 46 
705 70 
805 40 

每处获得总票数

但是如果我想要得到每个候选人得票数的百分比呢?我需要在每个数据对象上应用某种功能吗?理想情况下,我想最终的数据对象的样子:

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

回答

2

首先,创建一个帧具有由候选人和办公室的选票。

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

然后,您可以通过办公室聚合并使用转换(它将返回像索引数据)来计算办公室的百分比。

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