Get n-smallest values from a particular column in Pandas DataFrame

Get n-smallest values from a particular column in Pandas DataFrame

To get the n smallest values from a particular column in a Pandas DataFrame, you can use the nsmallest() function.

Here's how to do it:

  • First, ensure you have the pandas library installed:
pip install pandas 
  • Next, you can use the nsmallest() function on the DataFrame:
import pandas as pd # Sample DataFrame data = { 'A': [1, 5, 3, 8, 6], 'B': [10, 20, 30, 40, 50] } df = pd.DataFrame(data) # Get the 3 smallest values from column 'A' n_smallest_values = df['A'].nsmallest(3) print(n_smallest_values) 

The output will be:

0 1 2 3 1 5 Name: A, dtype: int64 

If you want the entire rows for the n smallest values from the column, you can use:

n_smallest_rows = df.nsmallest(3, 'A') print(n_smallest_rows) 

This will return:

 A B 0 1 10 2 3 30 1 5 20 

In this example, we're getting the 3 smallest values from column 'A', but you can adjust the number and the column name as per your needs.


More Tags

wiremock word-wrap odbc task-parallel-library picasso fatal-error browser-scrollbars pypdf device-admin aws-sdk-js

More Programming Guides

Other Guides

More Programming Examples