繁体   English   中英

找到两列之间差异最大的行

[英]Find the row which has the maximum difference between two columns

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

对于以下 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']))
Traceback (most recent call last):

  File "", line 1, in 
    df.where(max(df['Gold']-df['Gold.1']))

  File "../python3.5/site-packages/pandas/core/generic.py", line 5195, in where
    raise_on_error)

  File "../python3.5/site-packages/pandas/core/generic.py", line 4936, in _where
    raise ValueError('Array conditional must be same shape as '

ValueError: Array conditional must be same shape as self

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

相反的.where ,您可以使用.idxmax

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

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

如果要查找绝对差最大的行,则可以先调用.abs()

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

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

x= list((df['col1']-df['col2']).abs())
x.index(max(x))
pd.Series(df['Gold']-df['Gold.1']).argmax()

或使用 numpy 库

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

大熊猫中的 argmax()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM