pandas.core.groupby.SeriesGroupBy.nlargest#
- SeriesGroupBy.nlargest(n=5, keep='first')[源代码]#
返回最大的 n 个元素。
- Parameters:
- nint,默认 5
返回按降序排序的前 N 个值。
- keep{‘first’, ‘last’, ‘all’},默认为 ‘first’
当存在重复值且无法全部放入大小为 n 的 Series 中时:
first: 按出现顺序返回前 n 个出现。last: 按出现顺序的逆序返回最后 n 个出现。all: 保留所有出现。这可能导致 Series 的大小大于 n。
- Returns:
- Series
Series 中按降序排列的 n 个最大值。
参见
Series.nsmallest获取 n 个最小值。
Series.sort_values根据值对 Series 进行排序。
Series.head返回前`n`行。
Notes
相比
.sort_values(ascending=False).head(n),对于 n 远小于 Series 对象大小的情况,速度更快。Examples
>>> countries_population = {"Italy": 59000000, "France": 65000000, ... "Malta": 434000, "Maldives": 434000, ... "Brunei": 434000, "Iceland": 337000, ... "Nauru": 11300, "Tuvalu": 11300, ... "Anguilla": 11300, "Montserrat": 5200} >>> s = pd.Series(countries_population) >>> s Italy 59000000 France 65000000 Malta 434000 Maldives 434000 Brunei 434000 Iceland 337000 Nauru 11300 Tuvalu 11300 Anguilla 11300 Montserrat 5200 dtype: int64
n 个最大元素,默认 n=5。
>>> s.nlargest() France 65000000 Italy 59000000 Malta 434000 Maldives 434000 Brunei 434000 dtype: int64
n 个最大元素,n=3。默认 keep 值为 ‘first’,因此会保留 Malta。
>>> s.nlargest(3) France 65000000 Italy 59000000 Malta 434000 dtype: int64
n 个最大元素,n=3,并保留最后一个重复值。由于 Malta 是具有值 434000 的最后一个,因此会保留 Malta,这是基于索引顺序的。
>>> s.nlargest(3, keep='last') France 65000000 Italy 59000000 Brunei 434000 dtype: int64
n 个最大元素,n=3,并保留所有重复值。请注意,由于存在三个重复值,返回的 Series 包含五个元素。
>>> s.nlargest(3, keep='all') France 65000000 Italy 59000000 Malta 434000 Maldives 434000 Brunei 434000 dtype: int64