首页 > 解决方案 > pandas argmax 返回一个意外的值

问题描述

我通过 print 调用 argmax 函数:

print(piTot)
print(piTot[piTot.argmax()],",",piTot.argmax())

并获得以下输出:

0        0.000000
1      137.077960
2      258.248535
3      452.867526
4      526.315944
5      583.856975
6      625.490621
7      651.216882
14     661.035756
8      654.947245
15     632.951348
9      595.048066
16     541.237397
10     471.519343
11     385.893904
12     284.361079
17     166.920868
18      33.573271
19    -115.681712
13    -280.844080
20    -461.913834
21    -658.890973
22    -871.775498
23   -1100.567409
24   -1345.266706
dtype: float64
654.9472450175853 , 8

我正在寻找的输出是:

661.035756 , 14

问题出在哪里,因为我看不到它。

标签: pythonpandasnumpy

解决方案


  • 在您的示例中,piTotpandas.Series.
    • 我通过将价格序列与相应的 ols 估计值相乘来生成 piTot
      • 这创建了一个pandas.Serieswhere the dtypeisfloat64
    • 给定DataFrame, df, 下面,你的等价物SeriespiTot = df['val']
    • 您正在使用 a Series,这就是为什么piTot[piTot.argmax()]不导致 aKeyError
      • 预期值需要索引号,piTot[piTot.idxmax()]而不是索引标签。
  • .argmax()请注意与相比,返回的内容的差异.idxmax()
# Return index of first occurrence of maximum over requested axis.
idx = df['val'].idxmax()

# Return int position of the largest value in the Series.
arg = df['val'].argmax()

print(idx, arg)
[out]:
(14, 8)

# use loc with the label
df.loc[idx]
[out]:
1    661.035756
Name: 14, dtype: float64

# use iloc with the int position
df.iloc[arg]
1    661.035756
Name: 14, dtype: float64
print(f'Use iloc with argmax:\n{df.iloc[arg]}')
print(f'\nNumeric Location: {arg}')
print(f'\nUse loc with idxmax\n{df.loc[idx]}')
print(f'\nLabel Location: {idx}')
[out]:
Use iloc with argmax:
val    661.035756
Name: 14, dtype: float64

Numeric Location: 8

Use loc with idxmax
val    661.035756
Name: 14, dtype: float64

Label Location: 14

数据

# create dataframe from clipboard
df = pd.read_clipboard(sep=',', index_col=[0])

# copy to clipboard
,val
0,0.0
1,137.07796
2,258.248535
3,452.867526
4,526.315944
5,583.856975
6,625.490621
7,651.216882
14,661.035756
8,654.947245
15,632.951348
9,595.048066
16,541.237397
10,471.519343
11,385.893904
12,284.361079
17,166.920868
18,33.573271
19,-115.681712
13,-280.84408
20,-461.913834
21,-658.890973
22,-871.775498
23,-1100.567409
24,-1345.266706

推荐阅读