Get topmost N records within each group
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 ]}) df |
Output:
Variables Value 0 A 2 1 A 5 2 A 0 3 A 3 4 B 1 5 B 0 6 B 9 7 C 0 8 C 7 9 C 5 10 C 4
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.