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

佐手、 提交于 2021-02-05 07:28:28

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/54895311/get-column-names-for-the-n-max-min-values-per-row-in-pandas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!