Matan Solomon
Matan Solomon

Reputation: 171

Indices of smallest n values over whole Pandas DF

I'm searching for an efficient way to extract the indices of the n smallest values over the whole data frame.

For example, given the following df with n = 2:

    colA    colB    colC
r1   33      75      22
r2    1      52      95
r3   71       7      68

I would like to get, in some form, the indices [(r2, colA), (r3, colB)] corresponding to the 2 smallest values over the whole df: 1 and 7.

The order between the indices is not important (The corresponding values may not be sorted).

Thanks!

Upvotes: 2

Views: 695

Answers (3)

Matan Solomon
Matan Solomon

Reputation: 171

In addition to Neo's answer, in the meanwhile, I found the following solution:

n=2
list(df.stack().sort_values().head(n).index)

Screenshot

Upvotes: 3

NeoTheNerd
NeoTheNerd

Reputation: 656

nsmallest -

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.nsmallest.html

import pandas as pd
df=pd.DataFrame({"colA":[33,1,71],"colB":[75,52,7],"colC":[22,95,68]})

df.apply(pd.Series.nsmallest, axis=1, n=1)

df.apply(pd.Series.nsmallest, axis=1, n=2)

nsmallest example

Upvotes: 2

NeoTheNerd
NeoTheNerd

Reputation: 656

df.min

import pandas as pd
df=pd.DataFrame({"colA":[33,1,71],"colB":[75,52,7],"colC":[22,95,68]})

#The min value for each numerical column in the dataframe
df.min(numeric_only=True)

#The minimum value in the entire dataframe
df.min(numeric_only=True).min()

df.min example

Upvotes: 0

Related Questions