python的nlargest_python pandas DataFrame.nlargest用法及代码示例

返回第一个n行排序columns降序排列。

返回第一个n在中具有最大值的行columns,按降序排列。未指定的列也将返回,但不用于排序。

此方法等效于df.sort_values(columns, ascending=False).head(n),但性能更高。

参数:

n:int要返回的行数。

columns:label 或 list of labels要排序的列标签。

keep:{‘first’, ‘last’, ‘all’}, 默认为 ‘first’有重复值的地方:

first:优先处理首次出现的事件

last:优先排列最后一次出现的

alldo not drop any duplicates, even it means选择多个n项目。

0.24.0版中的新功能。

返回值:

DataFrame首先n给定列按降序排列的行。

注意:

并非所有列类型都可以使用此功能。例如,当用object或者categorydtypesTypeError被提出。

例子:

>>> df = pd.DataFrame({'population': [59000000, 65000000, 434000,

... 434000, 434000, 337000, 11300,

... 11300, 11300],

... 'GDP': [1937894, 2583560 , 12011, 4520, 12128,

... 17036, 182, 38, 311],

... 'alpha-2': ["IT", "FR", "MT", "MV", "BN",

... "IS", "NR", "TV", "AI"]},

... index=["Italy", "France", "Malta",

... "Maldives", "Brunei", "Iceland",

... "Nauru", "Tuvalu", "Anguilla"])

>>> df

population GDP alpha-2

Italy 59000000 1937894 IT

France 65000000 2583560 FR

Malta 434000 12011 MT

Maldives 434000 4520 MV

Brunei 434000 12128 BN

Iceland 337000 17036 IS

Nauru 11300 182 NR

Tuvalu 11300 38 TV

Anguilla 11300 311 AI

在下面的示例中,我们将使用nlargest选择列“population”中具有最大值的三行。

>>> df.nlargest(3, 'population')

population GDP alpha-2

France 65000000 2583560 FR

Italy 59000000 1937894 IT

Malta 434000 12011 MT

使用时keep='last',关系以相反的顺序解决:

>>> df.nlargest(3, 'population', keep='last')

population GDP alpha-2

France 65000000 2583560 FR

Italy 59000000 1937894 IT

Brunei 434000 12128 BN

使用时keep='all',所有重复项都将保留:

>>> df.nlargest(3, 'population', keep='all')

population GDP alpha-2

France 65000000 2583560 FR

Italy 59000000 1937894 IT

Malta 434000 12011 MT

Maldives 434000 4520 MV

Brunei 434000 12128 BN

要按“population”列然后按“GDP”列中的最大值排序,我们可以像下面的示例一样指定多个列。

>>> df.nlargest(3, ['population', 'GDP'])

population GDP alpha-2

France 65000000 2583560 FR

Italy 59000000 1937894 IT

Brunei 434000 12128 BN


版权声明:本文为weixin_30160357原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。