RandomGuy42
RandomGuy42

Reputation: 321

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.

Upvotes: 4

Views: 2418

Answers (2)

cs95
cs95

Reputation: 402393

If the order of the largest/smallest and second largest/smallest values don't matter, then you can use np.argpartition.

N = 2 # Number of min/max values 
u = np.argpartition(df, axis=1, kth=N).values
v = df.columns.values[u].reshape(u.shape)

maxdf = pd.DataFrame(v[:,-N:]).rename(columns=lambda x: f'Max{x+1}')
mindf = pd.DataFrame(v[:,:N]).rename(columns=lambda x: f'Min{x+1}')

pd.concat([df, maxdf, mindf], axis=1)

     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    b    c    a    d
3  3.3  7.8  0.12  3.2  1.40    a    b    c    e

Upvotes: 1

Andy Hayden
Andy Hayden

Reputation: 375445

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

Upvotes: 2

Related Questions