maxframe.dataframe.DataFrame.nsmallest#

DataFrame.nsmallest(n, columns, keep='first')#

返回按 columns 升序排列的前 n 行。

返回 columns 中值最小的前 n 行,按升序排列。未指定的列也会返回,但不用于排序。

此方法等价于 df.sort_values(columns, ascending=True).head(n),但性能更优。

参数:
  • n (int) -- 要检索的项目数量。

  • columns (list or str) -- 用于排序的列名或列名列表。

  • keep ({'first', 'last', 'all'}, default 'first') -- 当存在重复值时: - first : 取首次出现的。 - last : 取最后出现的。 - all : 不删除任何重复项,即使这意味着选择超过 n 项。

返回类型:

DataFrame

参见

DataFrame.nlargest

返回按 columns 降序排列的前 n 行。

DataFrame.sort_values

按值对 DataFrame 进行排序。

DataFrame.head

返回前 n 行而不重新排序。

示例

>>> import maxframe.dataframe as md
>>> df = md.DataFrame({'population': [59000000, 65000000, 434000,
...                                   434000, 434000, 337000, 337000,
...                                   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.execute()
          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         337000      182      NR
Tuvalu         11300       38      TV
Anguilla       11300      311      AI

在下面的示例中,我们将使用 nsmallest 来选择 "population" 列中值最小的三行。

>>> df.nsmallest(3, 'population').execute()
          population    GDP alpha-2
Tuvalu         11300     38      TV
Anguilla       11300    311      AI
Iceland       337000  17036      IS

当使用 keep='last' 时,重复项按相反顺序处理:

>>> df.nsmallest(3, 'population', keep='last').execute()
          population  GDP alpha-2
Anguilla       11300  311      AI
Tuvalu         11300   38      TV
Nauru         337000  182      NR

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

>>> df.nsmallest(3, 'population', keep='all').execute()
          population    GDP alpha-2
Tuvalu         11300     38      TV
Anguilla       11300    311      AI
Iceland       337000  17036      IS
Nauru         337000    182      NR

要按 "population" 列中的最小值排序,然后按 "GDP" 排序,可以像下一个示例中那样指定多个列。

>>> df.nsmallest(3, ['population', 'GDP']).execute()
          population  GDP alpha-2
Tuvalu         11300   38      TV
Anguilla       11300  311      AI
Nauru         337000  182      NR