You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何通过每日切片极值索引获取原数组对应值?

解决局部极值索引取值的TypeError问题

核心原因

argrelextrema返回的是numpy数组格式的位置索引,你尝试用day_hours[maxima]获取标签后索引spot_price时触发报错,本质是数据类型不匹配:如果spot_price是pandas Series,直接用方括号做标签索引时,numpy数组类型的索引会引发TypeError;如果spot_price是numpy数组,完全不需要经过day_hours,直接用位置索引即可。

正确取值方案

根据你的数据类型选择对应方法:

  1. 如果spot_price是pandas Series
    用iloc按位置索引取值(和argrelextrema返回的位置索引逻辑完全匹配):

    max_values = spot_price.iloc[maxima]
    
  2. 如果spot_price是numpy数组
    直接用maxima作为索引取值,无需借助day_hours:

    max_values = spot_price[maxima]
    
  3. 必须使用day_hours标签索引的场景
    把numpy数组类型的maxima转换成列表,再获取标签后索引:

    max_labels = day_hours[list(maxima)]
    max_values = spot_price[max_labels]
    

快速排查验证

先打印以下内容确认数据类型,方便定位问题:

print(type(maxima))       # 应为 numpy.ndarray
print(type(spot_price))   # 确认是 pandas.Series 还是 numpy.ndarray
print(type(day_hours))    # 应为 pandas.RangeIndex

内容的提问来源于stack exchange,提问作者Janne Hirvonen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 10:47:12