获取 Pandas 中每行 N 个最大/最小值的列名 [英] Get column names for the N Max/Min values per row in Pandas

查看:64
本文介绍了获取 Pandas 中每行 N 个最大/最小值的列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为每一行获取最大值/最小值最多为 N 个值的列的名称.

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

鉴于这样的事情:

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

我可以使用 idxmax(axis=1) 获得最大值,依此类推 idxmin(axis=1) 的最小值,但这仅适用于 top-max和底部最小值,不可推广到 N 值.

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.

我想得到,如果用 N=2 调用:

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

我知道我总是可以获取行数据,计算第 N 个值并按索引映射到列名列表,只是想知道如果可能的话,有更好、更优雅的方法.

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.

推荐答案

您可以使用 nlargest 和 nsmallest:

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

这篇关于获取 Pandas 中每行 N 个最大/最小值的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆