2016-11-11 63 views
1

我试图创建是按以下格式投票数据的数据帧:简单的方法来创建多个列与多个行共享的大熊猫同一个键一行

Name,StateCode,GeoStratum,CountyCode,fips,Precinct,PrecinctReport,TotalVotes,FullName,VoteCount,ElectoralVote,Percent 
Hawaii,HI,2,1,15001,43,43,64865,Hillary Clinton,64 
Hawaii,HI,2,1,15001,43,43,64865,Donald Trump,27 
Hawaii,HI,2,1,15001,43,43,64865,Gary Johnson,4 
Hawaii,HI,2,1,15001,43,43,64865,Jill Stein,4 

我想将这些数据转换成格式是这样的:

Name,StateCode,GeoStratum,CountyCode,fips,Precinct,PrecinctReport,TotalVotes,FullName,VoteCount,ElectoralVote,Clinton,Trump,Johnson,Stein 
    Hawaii,HI,2,1,15001,43,43,64865,64,27,4,4 

有没有采取fips列作为键,然后从使用百分比值的简单方法,其中“希拉里·克林顿”或“川普”等。是FullName中的值来填充Trump,Clinton等栏目?

当然,一对夫妇嵌套循环会做到这一点。希望找到一个好方法。

回答

2

使用pivot_table和申报指标,列,和值要在转动的数据来获得:

df.pivot_table(index=['Name', 'StateCode', 'GeoStratum', 'CountyCode', 'fips', 'Precinct', 
     'PrecinctReport', 'TotalVotes'], columns='FullName', values='VoteCount') 

最终使用reset_index得到你所需要的表和删除无用列,可以保持从这个支点。