w3resource

Pandas: Get lowest n records within each group of a given DataFrame


81. Get Lowest n Records Within Each Group

Write a Pandas program to get lowest n records within each group of a given DataFrame.

Sample Solution :

Python Code :

import pandas as pd
d = {'col1': [1, 2, 3, 4, 7, 11], 'col2': [4, 5, 6, 9, 5, 0], 'col3': [7, 5, 8, 12, 1,11]}
df = pd.DataFrame(data=d)
print("Original DataFrame")
print(df)
print("\nLowest n records within each group of a DataFrame:")
df1 = df.nsmallest(3, 'col1')
print(df1)
df2 = df.nsmallest(3, 'col2')
print(df2)
df3 = df.nsmallest(3, 'col3')
print(df3)

Sample Output:

Original DataFrame
   col1  col2  col3
0     1     4     7
1     2     5     5
2     3     6     8
3     4     9    12
4     7     5     1
5    11     0    11

Lowest n records within each group of a DataFrame:
   col1  col2  col3
0     1     4     7
1     2     5     5
2     3     6     8
   col1  col2  col3
5    11     0    11
0     1     4     7
1     2     5     5
   col1  col2  col3
4     7     5     1
1     2     5     5
0     1     4     7

For more Practice: Solve these Related Problems:

  • Write a Pandas program to group a DataFrame by a specific column and then extract the lowest n records from each group using nsmallest().
  • Write a Pandas program to partition a DataFrame by groups and then select the bottom n rows for each group based on a numeric column.
  • Write a Pandas program to group a DataFrame and then use a custom aggregation function to retrieve the n smallest values per group.
  • Write a Pandas program to extract the lowest n records within each group and then merge the groups into a single DataFrame with a hierarchical index.

Go to:


Previous: Write a Pandas program to check for inequality of two given DataFrames.
Next: Pandas Indexing Exercises Home.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.