我发现 idxmax()
在 argmax()
不起作用的情况下有效(例如在整个数据帧上),但是在某些情况下我需要 argmax()
?如果不是,我会把它从我的脑海中抹去。
最佳答案
有区别。 pd.DataFrames
和pd.Series
有一个索引,该索引可能不连续,例如[0 ... n)
,但是当您在创建过程中未指定它时。因此人们常常将它们混淆。
考虑这个抛物线
import pandas as pd
import numpy as np
data = pd.Series(16 - np.arange(-4,5) ** 2)
0 0
1 7
2 12
3 15
4 16
5 15
6 12
7 7
8 0
dtype: int64
标签设置为 [0 ... 9)
,因为我们没有指定它们。在这种情况下,data.argmax()
和data.idxmax()
结果是4
,因为这是 16
的整数位置和标签.
但是,如果我们过滤掉奇数值,则索引不再连续:
filtered = data[data % 2 == 0]
0 0
2 12
4 16
6 12
8 0
dtype: int64
在这里,filtered.argmax()
返回2
而filtered.idxmax()
返回4
.
当您想要引用 data
时,这一点尤其重要。 ,使用从 filtered
中提取的条目。即data.loc[4]
将通过未过滤的版本返回找到的值。
关于python - 我可以在所有情况下使用 idxmax() 代替 argmax() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47596390/