简体   繁体   English

熊猫数据框列上的条件逻辑

[英]Conditional Logic on Pandas Dataframe Column

I am fairly new to Python, so forgive the possibly trivial question. 我对Python相当陌生,因此请原谅可能不重要的问题。

I am trying to generate Buy and Sell signals given a change in the RSI value I have calculated for a specific futures contract. 给定我为特定期货合约计算的RSI值的变化,我试图生成买入和卖出信号。 In my DataFrame , I have created a column called R S I which contains the values I am referencing, and what I would like to do is check each proceeding value according to a predetermined logic, and if that criteria is met , Generate "Buy" or "Sell", then increment a count for each signal generated. 在我的DataFrame ,我创建了一个名为R S I的列,其中包含我要引用的值,我想要做的是根据预定的逻辑检查每个过程值,如果满足该条件,请生成“购买”或“出售”,然后为每个生成的信号增加计数。 ie I imagine a solution that compares [i] and [i+1] using a for loop , but I get an error that reads - 即我想象一个解决方案,它使用for循环比较[i][i+1] ,但出现错误,显示为-

TypeError: cannot do label indexing on class'pandas.indexes.range.RangeIndex with these indexers [25.714285714285722] of class 'numpy.float64'

This is my code 这是我的代码

for i in es.RSI:
    Buy = 0
    Sell = 0
    if es.RSI[i] < 30.0 and es.RSI[i+1] >30.0:
        es.RSI[i] = "Buy"
        Buy = Buy +1

    if es.RSI[i] >70.0 and es.RSI[i+1] < 70.0 :
        es.RSI[i] = "Sell"
        Sell = Sell +1

Based on the error, it looks like you're using a float for an array index value. 基于该错误,看来您正在使用浮点数作为数组索引值。 Perhaps try replacing each index of 也许尝试替换的每个索引

es.RSI[i]

with

es.RSI[int(i)]

(Same thing with es.RSI[i+1], replace it with es.RSI[int(i)+1].) (与es.RSI [i + 1]相同,请替换为es.RSI [int(i)+1]。)

Your loop 你的循环

for i in es.RSI:

iterate over items from er.RSI array, so your i contains value of RSI, not index of array. 迭代er.RSI数组中的项,因此您的i包含RSI的值,而不是数组的索引。 That's why you see this error 这就是为什么您看到此错误

TypeError: cannot do label indexing on class'pandas.indexes.range.RangeIndex with these indexers [25.714285714285722] of class 'numpy.float64'

To iterate over array index you should use 要遍历数组索引,您应该使用

for i in range(len(es.RSI)-1):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM