我希望在一个数据帧被分组后,得到其中一些值的总和。你知道吗
一些示例数据:
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
首先,创建一个包含候选人和办公室投票的框架。你知道吗
然后,您可以按office进行聚合,并使用一个转换(像索引数据一样返回)来计算office的百分比。你知道吗
相关问题 更多 >
编程相关推荐