How to use nlargest() function of pandas to group the columns In Python Pandas
Now, we will get topmost N values of each group of the ‘Variables’ column. Here nlargest() function is used to get the n largest values in the specified column.
Python3
# importing pandas as pd import pandas as pd # creating dataframe df = pd.DataFrame({ 'Variables' : [ 'A' , 'A' , 'A' , 'A' , 'B' , 'B' , 'B' , 'C' , 'C' , 'C' , 'C' ], 'Value' : [ 2 , 5 , 0 , 3 , 1 , 0 , 9 , 0 , 7 , 5 , 4 ]}) #print(df) d = df.nlargest( 4 , 'Value' ) print (d) |
Output:
Variables Value 6 B 9 8 C 7 1 A 5 9 C 5
Get topmost N records within each group of a Pandas DataFrame
Firstly, the pandas dataframe stores data in the form of a table. In some situations we need to retrieve data from dataframe according to some conditions. Such as if we want to get top N records of each group of the dataframe. We create the dataframe and use the methods mentioned below.