我正在使用 Pandas 来分析一些选举结果。我有一个DF,结果,其中每个选区都有一行,代表各政党(其中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 中,有什么方法可以为每一行返回一组列中的第二个最高值/索引吗?
最佳答案
要获得列的最高值,可以使用nlargest():
df['High'].nlargest(2)
上面将为您提供
High
列的2个最高值。您也可以以相同的方式使用nsmallest()来获取最低值。
关于python - 在 Pandas 列中获取第一和第二高值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39066260/