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

使用mplfinance绘制1分钟K线图遇AttributeError错误求助

解决mplfinance绘制K线图的AttributeError问题

错误原因

你用resample().agg()生成的OHLC数据是多级列索引,列名是类似('price', 'first')的元组(tuple)。而mplfinance在处理数据时,会尝试对列名调用strip()方法(字符串专属方法),但元组没有该方法,因此触发AttributeError: 'tuple' object has no attribute 'strip'。

修正方案

方案1:重命名已生成的OHLC列

直接修改ohlc的列名,将多级索引转为mplfinance要求的单级列名(需为Open、High、Low、Close,大小写不敏感,建议规范命名):

prices = df['price']
time = pd.to_datetime(df['ts_event'])

sample_df = pd.DataFrame({'time': time, 'price': prices})

# 生成OHLC数据
ohlc = sample_df.set_index('time').resample('min').agg({'price': ['first', 'max', 'min', 'last']})

# 关键:重命名列,去除多级索引
ohlc.columns = ['Open', 'High', 'Low', 'Close']

# 绘制K线图
import mplfinance as mplf
mplf.plot(ohlc, type='candle')
mplf.show()

方案2:聚合时直接指定列名(更简洁)

在agg()中直接定义列名,避免生成多级索引:

prices = df['price']
time = pd.to_datetime(df['ts_event'])

sample_df = pd.DataFrame({'time': time, 'price': prices})

# 聚合时直接指定列名,生成单级索引的DataFrame
ohlc = sample_df.set_index('time').resample('min').agg(
    Open=('price', 'first'),
    High=('price', 'max'),
    Low=('price', 'min'),
    Close=('price', 'last')
)

# 绘制K线图
import mplfinance as mplf
mplf.plot(ohlc, type='candle')
mplf.show()

验证说明

修改后,ohlc的列名会变成Open、High、Low、Close的单级索引,mplfinance可以正常识别并处理数据,不会再触发元组相关的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 17:37:21