我正在用熊猫分析一些选举结果。我有一个DF,Results,每个选区有一行,代表不同党派的选票(超过100人):
In[60]: Results.columns
Out[60]:
Index(['Constituency', 'Region', 'Country', 'ID', 'Type', 'Electorate',
'Total', 'Unnamed: 9', '30-50', 'Above',
...
'WP', 'WRP', 'WVPTFP', 'Yorks', 'Young', 'Zeb', 'Party', 'Votes',
'Share', 'Turnout'],
dtype='object', length=147)
所以。。。
In[63]: Results.head()
Out[63]:
Constituency Region Country ID Type \
PAID
1 Aberavon Wales Wales W07000049 County
2 Aberconwy Wales Wales W07000058 County
3 Aberdeen North Scotland Scotland S14000001 Burgh
4 Aberdeen South Scotland Scotland S14000002 Burgh
5 Aberdeenshire West & Kincardine Scotland Scotland S14000058 County
Electorate Total Unnamed: 9 30-50 Above ... WP WRP WVPTFP \
PAID ...
1 49821 31523 NaN NaN NaN ... NaN NaN NaN
2 45525 30148 NaN NaN NaN ... NaN NaN NaN
3 67745 43936 NaN NaN NaN ... NaN NaN NaN
4 68056 48551 NaN NaN NaN ... NaN NaN NaN
5 73445 55196 NaN NaN NaN ... NaN NaN NaN
Yorks Young Zeb Party Votes Share Turnout
PAID
1 NaN NaN NaN Lab 15416 0.489040 0.632725
2 NaN NaN NaN Con 12513 0.415052 0.662230
3 NaN NaN NaN SNP 24793 0.564298 0.648550
4 NaN NaN NaN SNP 20221 0.416490 0.713398
5 NaN NaN NaN SNP 22949 0.415773 0.751528
[5 rows x 147 columns]
每个政党的每个选区的结果都在Results.ix[:, 'Unnamed: 9': 'Zeb']
列中给出
我可以找到获胜的政党(即投票数最高的政党)及其投票数:
RawResults = Results.ix[:, 'Unnamed: 9': 'Zeb']
Results['Party'] = RawResults.idxmax(axis=1)
Results['Votes'] = RawResults.max(axis=1).astype(int)
但是,我还需要知道第二名政党获得了多少选票(最好是它的索引/名称)。那么在pandas中,是否有任何方法可以返回每一行的一组列中的second最高值/索引?
您可以对结果进行排序,使第一行包含最大值,然后您可以简单地使用索引来获取前n个位置。
要获取列的最高值,可以使用nlargest():
上面将给出列
High
的2最高值。您也可以使用nsmallest()同样的方法来获得最低的值。
下面是一个新的解决方案:
或者作为pandas数据帧:
或faster solution from @Divakar:
相关问题 更多 >
编程相关推荐