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

12

我有一个包含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']))
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('数组条件必须与自身形状相同')
ValueError: 数组条件必须与自身形状相同

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

3个回答

32

你可以使用.idxmax代替.where:

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

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

如果您想找到具有最大绝对值差异的行,则可以首先调用.abs()

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

0
pd.Series(df['Gold']-df['Gold.1']).argmax()

或者使用numpy库

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

pandas中的argmax()


0

虽然我的方法比上面的方法更长,但是那些熟悉列表操作的人可能会发现这很有用。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接