【问题标题】:Key error in python pandas while trying to compare values尝试比较值时python pandas中的关键错误
【发布时间】:2021-06-15 18:39:07
【问题描述】:

我正在尝试计算指数移动平均线(100 个周期的 EMA),为此,我有以下代码。它工作正常,但在我的熊猫中,我将把这个值与烛台的收盘值进行比较(从 binance 获取 200 周期 OHLCV 数据)我指定的条件是如果 ema - close KeyError: 'worth'我认为这与我在for循环中提到的值len(df.index) is 200的范围有关 请不要对last_fifty_rows 这个名字感到困惑,我一直在尝试不同的时期,因此得名。这里的任何见解都值得赞赏。谢谢

编辑:我在 cmets 中提到删除 [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))

【问题讨论】:

  • df['worth'] 在赋值之前必须是现有列。
  • @im0j 感谢您的回复。我在这里很困惑,如果我只使用 df['worth']=true 它可以工作,但计算会搞砸
  • 分配一个标量值(在本例中为'True')会用它初始化整个列,这不是您想要的。
  • @im0j 你建议我如何解决这个问题。我是否必须添加“价值”列,然后使用 df['worth'][current]='True'?我只是在学习和试验 python。抱歉,如果这是一个愚蠢的问题..
  • @im0j 非常感谢,我刚刚得到它我在循环之前初始化了 df['worth'] 的值,它解决了问题。祝你有美好的一天!!!

标签: python pandas


【解决方案1】:

如果有人在寻找这个,我解决了整个问题并通过在循环开始之前添加以下行来获得我想要的输出: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))

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 2021-12-14
    • 1970-01-01
    • 2013-04-11
    • 2017-08-05
    • 2016-07-18
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多