Change array values using for and if

Asked

Viewed 529 times

-1

Hello, I have an array with several values. I would like to replace the values above -0.54 to 1 and the values below -0.54 to 0.

Below is my results name array:

array([-2.06133692,  0.3721    , -1.35233125, -2.05725375,  0.39800875,
       -2.0544975 ,  0.66408308, -1.5466    ,  0.66212308, -2.559165  ,])

I tried to use the following code:

for x in resultados:
if x > -0.54:
    resultados = 1
else:
    resultados = 0

But what I get at the end is the value 0. I believe it iterates in the array and only stores each element, hence the latter is smaller, saves as 0 result.

The doubt may seem simple, but I’ve been stuck in it for a long time, and I don’t know how to solve it. Thanks in advance.

2 answers

2

From what I understand it’s this:

Your array is so:

array([-2.06133692,  0.3721    , -1.35233125, -2.05725375,  0.39800875,
       -2.0544975 ,  0.66408308, -1.5466    ,  0.66212308, -2.559165  ,])

But after the code, you want it like this:

array([0, 1, 0, 0, 1,
       0, 1, 0, 1, 0]) 

Correct?

If yes, use this code:

array=([-2.06133692,  0.3721    , -1.35233125, -2.05725375,  0.39800875,
       -2.0544975 ,  0.66408308, -1.5466    ,  0.66212308, -2.559165  ,])

for j in range(len(array)):
    if array[j] > -0.54:
        array[j]=1 
    else:
        array[j]=0

print(array)

Because to perform the desired replacement, you need to inform the content of list to assign a certain value.

1


Just like you said, in your code the for traverse each element of the array, assigning each loop an element of the array to the variable resultado. The problem is that when using the operator =, you do not add or replace a value in the array, in fact what you do is replace the array with another data.

Thus, as in the last loop that the for gives the element is less than -0.54, the value assigned to the variable will be zero. If your goal is to replace each array value by 1 or 0, you should use brackets after the variable name (I don’t know which language you’re using, but most languages use brackets to manipulate array elements) passing the index (position) element within the brackets, and then use allocation operator.

Below is an example of code written in Python (I chose Python because it has a structure similar to the code of your question)

posicao = 0

for x in resultados:

    if x > -0.54:
        resultados[posicao] = 1
    else:
        resultados[posicao] = 0
    posicao += 1
  • Thank you very much! It worked! I was having difficulties in this index, I believe that now I will not go through this problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.