Pandas 数据帧nlargest()方法

原文:https://www.studytonight.com/pandas/pandas-dataframe-nlargest-method

在本教程中,我们将讨论和学习 PandasDataFrame.nlargest()方法。该方法用于获取数据帧的第一n 行,该行按列降序排列。该方法按降序返回列中值最大的第一个n 行。未指定的列也会返回,但不用于排序。

下面是DataFrame.nlargest()方法的语法。

句法

DataFrame.nlargest(n, columns, keep='first')

因素

n: 它指定了 int,即要返回的行数。

列:它代表标签或标签列表,是要排序的列的名称。

keep: 包含‘first’‘last’‘all’,默认为‘first’

如果存在重复值:

  • 第一:优先处理第一个事件

  • 最后:优先考虑最后一次出现

  • all:不要删除任何重复项,即使这意味着选择了 n 个以上的项目。

示例 1:按降序获取数据帧

在下面的例子中,DataFrame.nlargest()方法按'Height'列降序返回第一个2 行的数据帧。

#importing pandas as pd
import pandas as pd
#creating DataFrame
df= pd.DataFrame({'Name':['Chetan','yashas','yuvraj','Pooja','Sindu','Renuka'],'Age':  [20,25,30,18,25,20],'Height': [155,160,175,145,155,165],'Weight': [75,60,75,45,55,65]})
print(df.nlargest(2,'Height'))

一旦我们运行该程序,我们将获得以下输出。

姓名年龄身高体重 2 yuvraj 30 175 75 5 雷努卡 20 165 65

示例 2:按降序获取数据帧

下例与上例类似,DataFrame.nlargest()方法按'Age'列降序返回第一个3 行的数据帧。

#importing pandas as pd
import pandas as pd
#creating DataFrame
df= pd.DataFrame({'Name':['Chetan','yashas','yuvraj','Pooja','Sindu','Renuka'],'Age':  [20,25,30,18,25,20],'Height': [155,160,175,145,155,165],'Weight': [75,60,75,45,55,65]})
print("--------The DataFrame is-------")
print(df.nlargest(3,'Age'))

一旦我们运行该程序,我们将获得以下输出。

-数据帧为- 姓名年龄身高体重 2 yuvraj 30 175 75 1 yashas 25 160 60 4 Sindu 25 155 55

示例 3:按降序获取数据帧

keep='last' 出现时,DataFrame.nlargest()方法优先处理指定列的最后一次出现,并返回数据帧

#importing pandas as pd
import pandas as pd
#creating DataFrame
df= pd.DataFrame({'Name':['Chetan','yashas','yuvraj','Pooja','Sindu','Renuka'],'Age':  [20,25,30,18,25,20],'Height': [155,160,175,145,155,165],'Weight': [75,60,75,45,55,65]})
print(df.nlargest(2,'Height',keep='last'))

一旦我们运行该程序,我们将获得以下输出。

姓名年龄身高体重 2 yuvraj 30 175 75 5 雷努卡 20 165 65

结论

在本教程中,我们学习了 PandasDataFrame.nlargest()方法。我们学习了语法、参数,并将其应用于数据帧,以理解 DataFrame.nlargest()方法。