使用pandas_ta计算Stoch RSI时报错ValueError: 传递2个元素预期1个
问题原因
pandas_ta库的ta.stochrsi()方法默认会同时返回*快K线(STOCHRSIk)和快D线(STOCHRSId)*两个序列,为2列的DataFrame结构。你尝试将2列数据直接赋值给df['stochrsi']这单个列,数据维度不匹配,因此触发了"Wrong number of items passed 2, placement implies 1"的报错。
解决方案
你可以根据自己的需求选择以下任意一种修改方式:
- 仅需要单个指标时,提取对应列再赋值
如果你只需要Stoch RSI的K值或者D值,先从返回结果中提取对应单列再赋值即可:def stoch_rsi(df, length=14): # 先获取stochrsi返回的完整结果 stochrsi_res = ta.stochrsi(close = df['close']) # 仅提取K值赋值,需要D值就替换为STOCHRSId_14_14_3_3 df['stochrsi'] = stochrsi_res['STOCHRSIk_14_14_3_3'] return df['stochrsi'] - 需要两个指标时,分别赋值给不同的列
如果你需要同时用到K和D两个值,分别创建两个列存储即可:def stoch_rsi(df, length=14): stochrsi_res = ta.stochrsi(close = df['close']) df['stochrsi_k'] = stochrsi_res['STOCHRSIk_14_14_3_3'] df['stochrsi_d'] = stochrsi_res['STOCHRSId_14_14_3_3'] return df[['stochrsi_k', 'stochrsi_d']] - 不确定列名时,先打印结果确认
如果你修改了stochrsi的默认参数(比如长度、平滑周期),返回的列名后缀会同步变化,可以先执行print(ta.stochrsi(close = df['close']).columns)查看实际列名,再对应提取即可。
修改后完整代码示例
import pandas as pd import pandas_ta as ta import numpy as np df = pd.read_csv('data/1d/AAVEUSDT-1d-data.csv') def stoch_rsi(df, length=14): stochrsi_res = ta.stochrsi(close = df['close']) df['stochrsi'] = stochrsi_res['STOCHRSIk_14_14_3_3'] return df['stochrsi'] stoch = stoch_rsi(df) print(stoch)
内容的提问来源于stack exchange,提问作者Louis
相关产品推荐
相关产品推荐

