numpy.argmax()对我排序的熊猫不起作用.系列



有人能向我解释一下为什么在我的熊猫系列上使用sort_values()argmax()函数不起作用吗?

下面是我的代码示例。输出中的索引基于原始DataFrame,而不是已排序的Series。

import pandas as pd
import numpy as np
df = pd.DataFrame({
'a': [4, 5, 3, 1, 2],
'b': [20, 10, 40, 50, 30],
'c': [25, 20, 5, 15, 10]
})
def sec_largest(x):
xsorted = x.sort_values(ascending=False)
return xsorted.idxmax()
df.apply(sec_largest)

然后输出为

a    1 
b    3 
c    0 
dtype: int64

当我使用xsorted.iloc[0]函数检查序列时,它会给我序列中的最大值。

有人能向我解释一下这是怎么回事吗?非常感谢。

问题是您对pandas系列使用排序,在排序时索引也会随之传递,idxmax返回值最高的原始索引,而不是排序系列的索引。。

def sec_largest(x):
xsorted = x.sort_values(ascending=False)
return xsorted.values.argmax()

通过使用xsorted的值,我们使用了numpy数据帧,而不是底层的panda数据结构,一切都按预期进行。

如果你在函数中打印xsorted,你可以看到索引也会按照进行排序

1    5
0    4
2    3
4    2
3    1

最新更新