Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python pandas-将列标签指定给记录值作为最小/最大函数的结果_Python_Pandas - Fatal编程技术网

Python pandas-将列标签指定给记录值作为最小/最大函数的结果

Python pandas-将列标签指定给记录值作为最小/最大函数的结果,python,pandas,Python,Pandas,提取列标签的最佳方法是什么?从中选择值作为最小或最大函数的结果?一个例子肯定会比我的措辞更好地说明这个问题: 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]: Meth

提取列标签的最佳方法是什么?从中选择值作为最小或最大函数的结果?一个例子肯定会比我的措辞更好地说明这个问题:

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
您只需使用获取最小值的索引值,请确保为行指定axis=1。还有一个对应的idxmax


你的答案是正确的。如果df['Method4']='N/A',或与其他字符串值混合,该怎么办?对除Method4之外的所有列执行idxmin操作是否足够简单?也许这是一个更好的问题,也是我应该问的问题,因为它将描述一个更真实的数据集。我不熟悉编辑带有公认答案的问题与提出新问题的礼仪。你通常会提出新问题。NaN/None值可以,但字符串有问题。要从列的子集中进行选择,例如仅从Method1和Method2中选择:df['BestMethod2']=df[['Method1','Method2'].idxminaxis=1或df.loc[:,['Method1','Method2'].idxminaxis=1
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