Home > Enterprise >  If Loop Output wrong
If Loop Output wrong

Time:08-12

Hello Everyone this might be a stupid question however I am absolutely new to python programming and I can't figure out what I am doing wrong in this if loop:

price_a = train_predict
price_b = df_eval_1_long_III.reshape(-1,1)
price_c = df_eval_1_last_day.reshape(-1,1)

a = price_a > price_c
b = price_b > price_c
c = price_a < price_c
d = price_b < price_c

m = 0 
n_m = 0
counter = 0
n_counter = 0 
inactive_counter = 0

for len in (train_predict):

    if ( a & b ).all():
        counter  = 1
        m  = (price_a - price_c)
    
    elif (c & d).all(): 
        n_counter  = 1
        n_m  = (price_a - price_c) * (-1)
    
    else: 
        inactive_counter  = 1

print (m)
print (n_m)
print (counter)
print (n_counter)
print (inactive_counter)

The loop gives following output:

0
0
0
0
2400

Now this apparently at least cycles through the array. When I change the for statement to for i in len(train_predict): I get the error message that numpy is not callable

The first 5 array values of each price are below

train_predict[:5]
array([[1.28537  ],
       [1.2874348],
       [1.2903055],
       [1.2867677],
       [1.2895652]], dtype=float32)

df_eval_1_last_day.reshape(-1,1)[:5]
array([[1.28910828],
       [1.28910828],
       [1.29190624],
       [1.28420818],
       [1.29250741]])

df_eval_1_long_III.reshape(-1,1)[:5]
array([[1.28910828],
       [1.29190624],
       [1.28420818],
       [1.29250741],
       [1.29377818]])

CodePudding user response:

I don't know a thing about numpy, and I'm lacking data, but maybe this will work?

a_and_b = a & b
c_and_d = c & d

for i, len in enumerate(train_predict):

    if a_and_b[i]:
        counter  = 1
        m  = (price_a - price_c)[i]
    
    elif c_and_d[i]: 
        n_counter  = 1
        n_m  = (price_a - price_c)[i] * (-1)
    
    else: 
        inactive_counter  = 1

Point is that you want to compare singular array items instead of the entire array.

Technically you shouldn't even use an external for loop with numpy as it defeats the purpose. Instead, just calculate the absolute value of price_a - price_c over the entire array (which is what it looks like you're trying to do) and sum everything accordingly.

  • Related