Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get column names for the N Max/Min values per row in Pandas

I am trying to get, for each individual row, the name of the column with the max/min value up to N-values.

Given something like this:

a     b     c     d     e
1.2   2     0.1   0.8   0.01
2.1   1.1   3.2   4.6   3.4
0.2   1.9   8.8   0.3   1.3
3.3   7.8   0.12  3.2   1.4

I can get the max with idxmax(axis=1) and so on the min with idxmin(axis=1) but this only works for the top-max and bottom-min, not generalizable for N-values.

I want to get, if called with N=2:

a     b     c     d     e     Max1    Max2    Min1    Min2    
1.2   2.0   0.1   0.8   0.1   b       a       c       e
2.1   1.1   3.2   4.6   3.4   d       d       b       a
0.2   1.9   8.8   0.3   1.3   c       b       a       d
3.3   7.8   0.1   3.2   1.4   b       a       c       e

I know I can always get the row data, calculate the N-th value and map to a list of columns-names by index, just wondering a better, more elegant way if possible.

like image 273
RandomGuy42 Avatar asked Oct 24 '25 10:10

RandomGuy42


1 Answers

You can use nlargest and nsmallest:

In [11]: res = df.apply(lambda x: pd.Series(np.concatenate([x.nlargest(2).index.values, x.nsmallest(2).index.values])), axis=1)

In [12]: res
Out[12]:
   0  1  2  3
0  b  a  e  c
1  d  e  b  a
2  c  b  a  d
3  b  a  c  e

In [13]: df[["Max1", "Max2", "Min1", "Min2"]] = res

In [14]: df
Out[14]:
     a    b     c    d     e Max1 Max2 Min1 Min2
0  1.2  2.0  0.10  0.8  0.01    b    a    e    c
1  2.1  1.1  3.20  4.6  3.40    d    e    b    a
2  0.2  1.9  8.80  0.3  1.30    c    b    a    d
3  3.3  7.8  0.12  3.2  1.40    b    a    c    e
like image 87
Andy Hayden Avatar answered Oct 27 '25 00:10

Andy Hayden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!