python - 尝试比较值时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))
解决方案
如果有人在寻找这个,我解决了整个问题并通过添加行获得了我想要的输出: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))
推荐阅读
- python - 使用 Python Websockets 库的多线程服务器
- react-native - 排毒错误:层次结构中找不到匹配的视图:(标签值:是“电子邮件”并且视图具有有效的可见性=可见)在 React Native 中
- string - 是否可以使用多个逗号分隔的字符串作为 TypeScript 类型?
- tensorflow - DeepLabV3,珊瑚的分割和分类/检测
- java - 致命异常:java.lang.RuntimeException - 由 java.lang.IllegalStateException 引起。应为 BEGIN_ARRAY,但为 BEGIN_OBJECT
- javascript - 将状态设置器传递给多个组件?
- python - 如何在 Python 中将 OHLC 值转换为 Renko 图?
- javascript - 应用程序从firebase缓慢获取大量数据反应本机
- eclipse - 配置 Eclipse/Jetty 解决问题:方法代码超出 65535 字节限制
- .net - .Net 5.0 是否具有 .Net Core 不具备的 WCF Web 服务功能?