擅长:python、mysql、java
<p>您可以将<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">^{<cd1>}</a>与<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nlargest.html" rel="nofollow noreferrer">^{<cd2>}</a>一起使用<code>.sort_values(ascending=False).head(n)</code>更快:</p>
<pre><code>print (census_df.set_index('CTYNAME')
.groupby('STNAME')['CENSUS2010POP']
.nlargest(3)
.sort_index(ascending=False)
.reset_index())
STNAME CTYNAME CENSUS2010POP
0 Wyoming Natrona County 75450
1 Wyoming Laramie County 91738
2 Wyoming Campbell County 46133
3 Wisconsin Winnebago County 166994
4 Wisconsin Waukesha County 389891
5 Wisconsin Washington County 131887
6 Alabama Etowah County 104430
7 Alabama Calhoun County 118572
8 Alabama Baldwin County 182265
</code></pre>
<p><code>3</code>顶值之和:</p>
^{pr2}$