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

Python 3.10用pandas-ta循环添加DataFrame指标报错求助

问题:循环调用pandas-ta指标时触发AttributeError错误

我在Python 3.10环境下用pandas-ta库,想写个函数接收DataFrame和指标名称字符串列表,把列表里的每个指标都添加到DataFrame中。

尝试写的代码:

import pandas_ta as ta

df = pd.DataFrame(data=BTC-USD)
indicators = ['rsi', 'obv']

for x in indicators:
    df[f'{x}'] = ta.x(df['close'])

单独添加rsi指标的正确写法示例:

df['rsi'] = ta.rsi(df['close'])

但运行循环时出现错误:

AttributeError: module 'pandas_ta' has no attribute 'x'

我是Python新手,想请教怎么解决这个问题?


解决方法

你出错的核心原因是:Python会把ta.x当成直接查找pandas_ta模块里名为x的属性,而不是把变量x的实际值(比如'rsi')作为属性名来调用对应函数。要动态调用模块中的函数,需要用getattr()方法来实现。

修正后的基础代码

import pandas as pd
import pandas_ta as ta

# 先正确读取数据(替换为你的实际数据路径或数据源)
df = pd.read_csv("你的数据文件.csv")
indicators = ['rsi', 'obv']

for indicator_name in indicators:
    # 动态获取ta模块中对应名称的函数
    indicator_func = getattr(ta, indicator_name)
    # 调用函数并将结果添加到DataFrame
    df[indicator_name] = indicator_func(df['close'])

扩展:处理需要多参数的指标

有些指标(比如OBV)需要成交量等额外参数,你可以用字典来存储指标和对应的参数,灵活扩展:

import pandas as pd
import pandas_ta as ta

df = pd.read_csv("你的数据文件.csv")
# 字典key是指标名,value是该指标需要的参数
indicators_with_params = {
    'rsi': {'close': df['close'], 'length': 20},  # 自定义RSI周期为20
    'obv': {'close': df['close'], 'volume': df['volume']}
}

for name, params in indicators_with_params.items():
    df[name] = getattr(ta, name)(**params)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 19:45:33