简体   繁体   中英

Conditional Logic on Pandas Dataframe Column

I am fairly new to Python, so forgive the possibly trivial question.

I am trying to generate Buy and Sell signals given a change in the RSI value I have calculated for a specific futures contract. 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. ie I imagine a solution that compares [i] and [i+1] using a for loop , but I get an error that reads -

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].)

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. 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):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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