【问题标题】:Pandas. ValueError: Length of values does not match length of index熊猫。 ValueError:值的长度与索引的长度不匹配
【发布时间】:2016-06-27 23:49:48
【问题描述】:

请帮忙!我的 SMA 和 EMA 代码结构几乎相同。 SMA 代码正常,但 EMA 代码出错:“ValueError:值的长度与索引的长度不匹配。”

SMA(简单移动平均线)代码:

import pandas as pd
import matplotlib.pyplot as plt
window_length = 20
df = pd.read_csv("TWII_2009-2011.csv")
df=df.set_index('Date')  #####
close = df['Close']
def simple_moving_average(window_length):
    sma=[]
    for i in range(len(close)):
        if i+1 < window_length:
            sma.append(0)
        else:
            sma.append(sum(close[i+1 - window_length : i+1])/window_length)
    return sma
df['SMA'] = simple_moving_average(window_length)

EMA(指数移动平均线)代码:

import pandas as pd
import matplotlib.pyplot as plt
window_length = 20
df = pd.read_csv("TWII_2009-2011.csv")
df=df.set_index('Date')  #####
close = df['Close']
def exponential_moving_average(window_length):
    ema = []
    j=1
    for i in range(len(close)):
        if i+1 < window_length:
            sma = sum(close[:window_length]) / window_length
            multiplier = 2 / float(1 + window_length)
            ema.append(sma)
            ema.append(( (close[window_length] - sma) * multiplier) + sma)
        else:
            tmp = ( (i - ema[j]) * multiplier) + ema[j]
            j = j + 1
            ema.append(tmp)
    return ema
df['EMA'] = exponential_moving_average(window_length)

【问题讨论】:

  • 我格式化了你的代码。但在未来.. 突出显示您的代码并按下编辑功能区上的 {} 按钮。
  • 你试过调试吗?
  • 您应该发布完整的回溯,因为这将确定错误的确切位置。
  • 错误显示在这一行 "df['EMA'] = Exponential_moving_average(window_length)"
  • @James:请将回溯添加到您的 question,而不是作为评论 - 阅读未格式化的 cmets 非常困难。

标签: python


【解决方案1】:

你附加了两次 ema!在第一个“If”语句中,而在 SMA 中,您只附加一次。删除一个..

for i in range(len(close)):
            if i+1 < window_length:
                sma = sum(close[:window_length]) / window_length
                multiplier = 2 / float(1 + window_length)
                ema.append(sma)
                ema.append(( (close[window_length] - sma) * multiplier) + sma)
            else:
                tmp = ( (i - ema[j]) * multiplier) + ema[j]
                j = j + 1
                ema.append(tmp)
        return ema

您应该查找用于这些计算的 pandas 方法。

【讨论】:

  • 我尝试过 ema.append(sma) 或 ema.append(( (close[window_length] - sma) * multiplier) + sma)。错误消失,但输出不是 ema 值。不管怎么说,还是要谢谢你!我将尝试为这些计算查找 pandas 方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
  • 2022-01-13
  • 1970-01-01
相关资源
最近更新 更多