Enumerate returns index -1 resulting in ValueError: Length of values does not match length of index

Enumerate returns index -1 resulting in ValueError: Length of values does not match length of index

我正在尝试在我的 df 中创建一个新列,类似于:

df["Signal"] = signalList

但是,我收到此错误 "Enumerate returns index -1 resulting in ValueError: Length of values does not match length of index"。所以我检查了我专栏的长度:

print(len(df["Crossover"]))

这个 returns 8192。所以我调整了代码以打印 *x 这样我就可以看到它上升到哪里,我得到 *8191。我怎样才能解决这个问题?干杯。

signalList = []
 for x,i in enumerate(df["Crossover"]):
print("*"+str(x))
if i == True:
    if df['EMA ' + str(emaShort)].iloc[x] > df['EMA ' + str(emaLong)].iloc[x]:
        signal = "Buy"
        signalList.append(signal)
    elif df['EMA ' + str(emaShort)].iloc[x] < df['EMA ' + str(emaLong)].iloc[x]:
        signal = "Sell"
        signalList.append(signal)
elif i != True:
    signal = "None"
    signalList.append(signal)

编辑 ********************************************* ******************************** 我想知道您能否告诉我是否可以调整下面的代码以利用矢量化处理。因为它快得多。第一段代码是我的尝试,它有点工作,下面的循环是我希望它准确工作的方式。我遇到的问题本质上是我需要第一个 buy/sell 信号之前的行是 "Position Column" 中的 None 但是,我无法得到向量化的 table 来做那。尽管它会准确地识别何时切换到 long/short,但信号之前的任何内容都将是 "Short",因为条件 returns 为假。我没有运气绕过这个。

df["Position"] = np.where(df['Signal'].ne("None"),np.where(df[f'Signal'].eq("Buy"), "Long", "Short"), np.where(df["Position"].shift(1).eq(True), "Long", np.where(df["Position"].shift(1).eq(False), "Short", "None")))

for x,i in enumerate(df['Signal']):
    if i == "Buy":
        df.iloc[x, df.columns.get_loc('Position')] = "Long"
    elif i == "Sell":
            df.iloc[x, df.columns.get_loc('Position')] = "Short"
    else:
        if df["Position"].iloc[x-1] == "Long":
            df.iloc[x, df.columns.get_loc('Position')] = "Long"
        elif df["Position"].iloc[x-1] == "Short":
            df.iloc[x, df.columns.get_loc('Position')] = "Short"
        else:
            df.iloc[x, df.columns.get_loc('Position')] = "None"

首先,您的代码中可能没有正确的缩进,正确的是

signalList = []
for x, i in enumerate(df["Crossover"]):
    print("*" + str(x))
    if i == True:
        if df['EMA ' + str(emaShort)].iloc[x] > df['EMA ' + str(emaLong)].iloc[x]:
            signal = "Buy"
            signalList.append(signal)
        elif df['EMA ' + str(emaShort)].iloc[x] < df['EMA ' + str(emaLong)].iloc[x]:
            signal = "Sell"
            signalList.append(signal)
    elif i != True:
        signal = "None"
        signalList.append(signal)

二、内if-elifelse; if

情况如何
df['EMA ' + str(emaShort)].iloc[x] == df['EMA ' + str(emaLong)].iloc[x]:

我想你的df中有一行满足这个条件

而不是你的 for 循环考虑以下:

import numpy as np

df['signal']=np.where(df['Crossover'], np.where(df[f'EMA {emaShort}'].lt(df[f'EMA {emaLong}']), 'Sell', 'Buy'), 'None')

您将以这种方式利用矢量化处理,这将使您的代码性能更好...