Skip to content Skip to sidebar Skip to footer

How To Use Nested For Loops In Python?

I'm trying to create an array based on values from another data frame in Python. I want it to fill the array as such. If x > or = 3 in the dataframe then it inputs a 0 in the ar

Solution 1:

When working with numpy arrays, it is more efficient if you can avoid using explicit loops in Python at all. (The actual looping takes place inside compiled C code.)

disc = df["disc"]

# make an array containing 0where disc >=3, elsewhere 1array= np.where(disc >=3, 0, 1)

# now set it equal to0inany places where disc ==0array[disc ==0] =0

It could also be done in a single statement (other than the initial assignment of disc) using:

array = np.where((disc >= 3) | (disc == 0), 0, 1)

Here the | does an element-by-element "or" test on the boolean arrays. (It has higher precedence than comparison operators, so the parentheses around the comparisons are needed.)

Solution 2:

This is a simple problem. There are many ways to solve this, I think the easiest way is to use a list. You can use a list and append the values according to the conditions.

array = []

for x in df["disc"]:
   if x >= 3:
       array.append(0)
   elif x < 3:
       array.append(1)
   else:
       array.append(0)

Solution 3:

Your code doesn't seem to be doing anything to the array, as you are trying to modify the variable y, rather than the array itself. y doesn't reference the array, it just holds the values found. The second loop also doesn't do anything due to the array being empty - it's looping through 0 elements. What you need rather than another for loop is to simply append to the array.

With a list, you would use the .append() method to add an element, however as you appear to be using numpy, you'd want to use the append(arr, values) function it provides, like so:

array = np.array([])

for x in df["disc"]:  
    if x >= 3:
        array = np.append(array, 0)
    elif x < 3:
        array = np.append(array, 1)
    else:
        array = np.append(array, 0)

I'll also note that these conditions can be simplified to combine the two branches which append a 0. Namely, if x < 3 and x is not 0, then add a 1, otherwise add a 0. Thus, the code can be rewriten as follows.

array = np.array([])

for x in df["disc"]:  
    if x < 3and x != 0:
        array = np.append(array, 1)
    else:
        array = np.append(array, 0)

Post a Comment for "How To Use Nested For Loops In Python?"