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

使用pandas DataFrame.idxmax()触发TypeError的解决问询

修复TypeError并获取最高价索引的解决方案

首先,这个错误的核心原因是close_price列的数据类型不是数值型(比如是字符串格式),而idxmax()方法只能对数值类型的列执行运算。咱们一步步来修复:

1. 先转换列的数据类型

读取数据后,先把close_price列转换成数值类型,同时处理可能存在的非数值数据(比如空字符串、异常值):

info = robinhood.RobinhoodHistoricalReader("AAPL", start=start, end=end, interval="5minute", span="day")
prices = pd.DataFrame(info.read(), columns=['close_price'])

# 转换为数值类型,errors='coerce'会把无法转换的值转为NaN
prices['close_price'] = pd.to_numeric(prices['close_price'], errors='coerce')
# 可选:删除包含NaN的行,避免干扰后续计算
prices = prices.dropna(subset=['close_price'])

2. 正确获取最高价的索引

你之前用prices.idxmax(axis=0)是对整个DataFrame按列找最大值索引,其实咱们只需要针对close_price这一列来操作就行:

# 获取最高价对应的行索引
max_price_index = prices['close_price'].idxmax()
# 计算对应的分钟数(假设索引是从0开始的整数,对应第n个5分钟区间)
minutes = max_price_index * 5

额外说明

如果你的prices的索引是时间戳类型(比如datetime),那max_price_index会直接返回最高价对应的时间,这时候你可以直接用这个时间戳来计算分钟数,而不需要乘以5,比如:

# 假设索引是datetime格式
minutes_since_start = (max_price_index - prices.index[0]).total_seconds() // 60

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:48:13