首页 > 解决方案 > 尝试比较值时python pandas中的关键错误

问题描述

我正在尝试计算指数移动平均线(100 个周期的 EMA),为此,我有以下代码。它工作正常,但在我的熊猫中,我将把这个值与烛台的收盘值进行比较(从 binance 获取 200 周期 OHLCV 数据)我指定的条件是如果 ema - close <0 那么它的价值是 true 否则 false到这里代码工作正常。问题是当条件发生变化时,所有先前的值也会发生变化(例如:如果倒数第二个值为假,而当前值为真,则全部变为真,反之亦然)我想要实现的是前一个值应该保持不变,重点应该放在当前值上我也得到了KeyError: 'worth'我认为这与我在 for 循环中提到的值的范围有关len(df.index) is 200 请不要混淆last_fifty_rows我一直在尝试不同时期的名称,因此名称。这里的任何见解都值得赞赏。谢谢

编辑:我在评论中提到删除 [current] 它会计算值,但 True/False 值不正确。我附上了输出的截图以供参考在此处输入图像描述

last_row_index = len(df.index) - 1
    previous_row_index = last_row_index - 1
    last_fifty_rows = len(df.index) - 100
    ema8 = ta.trend.ema_indicator(df['close'], 100)
        df['ema'] = ema8
        for current in range(last_fifty_rows, len(df.index)):
            previous = current - 1
            if (df['ema'][last_fifty_rows] - df['close'][last_fifty_rows]) < 0:
             df['worth'][current]= 'True' #......if changed to df['worth'] it works
            elif (df['ema'][last_fifty_rows] - df['close'][last_fifty_rows]) > 0:
             df['worth'][current]= 'False' #.....if changed to df['worth'] it works
            else:
                df['worth'][current]=df['worth'][previous]
    
        print(df.tail(5))

标签: pythonpandas

解决方案


如果有人在寻找这个,我解决了整个问题并通过添加行获得了我想要的输出:df['worth']=False在循环开始之前。

所以现在我的代码如下:

    last_row_index = len(df.index) - 1
    previous_row_index = last_row_index - 1
    last_fifty_rows = len(df.index) - 100
    df['worth']=False
    ema8 = ta.trend.ema_indicator(df['close'], 100)
        df['ema'] = ema8
        for current in range(last_fifty_rows, len(df.index)):
            previous = current - 1
            if (df['ema'][last_fifty_rows] - df['close'][last_fifty_rows]) < 0:
             df['worth'][current]= 'True' #......if changed to df['worth'] it works
            elif (df['ema'][last_fifty_rows] - df['close'][last_fifty_rows]) > 0:
             df['worth'][current]= 'False' #.....if changed to df['worth'] it works
            else:
                df['worth'][current]=df['worth'][previous]
    
        print(df.tail(5))

推荐阅读