pandas - 将列标签分配给记录值作为最小/最大函数

时间:2016-01-26 20:07:34

标签: python pandas

提取由min()max()函数选择值的列标签的最佳方法是什么?一个例子肯定会比我的措辞更好地说明这个问题:

import pandas as pd
df = pd.DataFrame({ 'Method1' : [10, 7, 3, 9, 7],
                    'Method2' : [10, 1, 5, 7, 8],
                    'Method3' : [5, 6, 2, 4, 10]})

In [3]: df
Out[3]: Method1     Method2     Method3
         10           10          5
          7           1           6
          3           5           2
          9           7           4
          7           8           10

现在,我想创建一个新列BestMethod,其中包含记录最低值的列名。我知道如何获得最低值(下面),但列名称呢?

In [4]: for i, row in df.iterrows():
              print min([r for r in row])
          5
          1
          2
          4
          7

所以最终结果看起来与此相似:

In [5]:   df
Out[5]:   Method1   Method2     Method3     BestMethod
              10         10           5       Method3
               7          1           6       Method2
               3          5           2       Method3
               9          7           4       Method3
               7          8          10       Method1

1 个答案:

答案 0 :(得分:4)

您可以简单地使用idxmin来获取最小值的索引值(确保为行指定axis = 1)。还有一个相应的idxmax

df['BestMethod'] = df.idxmin(axis=1)

>>> df
   Method1  Method2  Method3 BestMethod
0       10       10        5    Method3
1        7        1        6    Method2
2        3        5        2    Method3
3        9        7        4    Method3
4        7        8       10    Method1