【问题标题】:Find the row which has the maximum difference between two columns找到两列之间差异最大的行
【发布时间】:2017-04-18 13:25:03
【问题描述】:

我有一个包含GoldGold.1 列的DataFrame。我想找到这两列之差最大的那一行。

对于以下 DataFrame,这应该返回第 6 行。

df
Out: 
   Gold  Gold.1
0     2       1
1     1       4
2     6       9
3     4       4
4     4       8
5     5       5
6     5       2 ---> The difference is maximum (3)
7     5       9
8     5       3
9     5       6

我尝试使用以下内容:

df.where(max(df['Gold']-df['Gold.1']))

然而这引发了 ValueError:

df.where(max(df['Gold']-df['Gold.1'])) 回溯(最近一次通话最后): 文件“”,第 1 行,在 df.where(max(df['Gold']-df['Gold.1'])) 文件“../python3.5/site-packages/pandas/core/generic.py”,第 5195 行,在哪里 raise_on_error) 文件“../python3.5/site-packages/pandas/core/generic.py”,第 4936 行,在 _where raise ValueError('条件数组的形状必须与 ' ValueError:条件数组必须与自身的形状相同

如何找到满足此条件的行?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你可以用.idxmax代替.where

    (df['Gold'] - df['Gold.1']).idxmax()
    Out: 6
    

    这将返回差异最大的索引。

    如果你想找到最大绝对差异的行,那么你可以先调用.abs()

    (df['Gold'] - df['Gold.1']).abs().idxmax()
    Out: 4
    

    【讨论】:

      【解决方案2】:

      虽然我的方法比上面的方法长,但习惯使用列表的人可能会觉得这很有用。

      x= list((df['col1']-df['col2']).abs())
      x.index(max(x))
      

      【讨论】:

        【解决方案3】:
        pd.Series(df['Gold']-df['Gold.1']).argmax()
        

        或使用 numpy 库

        numpy.argmax(df['Gold']-df['Gold.1'])
        

        argmax() in pandas

        【讨论】:

          猜你喜欢
          • 2012-03-08
          • 2016-06-19
          • 2015-11-12
          • 2014-11-16
          • 2013-03-27
          • 1970-01-01
          • 1970-01-01
          • 2013-10-09
          • 1970-01-01
          相关资源
          最近更新 更多