Limzilla
Limzilla

Reputation: 1

Iterating two arrays in python with two different conditions

How do I iterate two sets of array with two different conditions? I am using iris data and trying to classify if it is versicolour or vigrinica.

array = dataframe.values
petalLength = array[50:,2]
petalWidth = array[50:,3]    

I'm trying to iterate two arrays, but not getting the results I need.

def decision(petalLength, petalWidth):
    for x in petalLength:
        for y in petalWidth:
            if x < 4.8 and y < 1.8:
                print("Versicolour")
            else:
                print("Virginica")

Results for example:

petal Length is 4.7 and petal Width is 1.5 the answer should be Versicolour
petal Length is 4.7 and petal width is 1.9 the answer should be Virginica

Upvotes: 0

Views: 58

Answers (3)

U13-Forward
U13-Forward

Reputation: 71570

Addition to schwobaseggl's answer, use return instead of print:

def decision(petalLength, petalWidth):
    for x, y in zip(petalLength, petalWidth):
        if x < 4.8 and y < 1.8:
            return "Versicolour"
        else:
            return "Virginica"

Then now:

print(decision(petalLength,petalWidth))

Will return as desired output,

But previously, it will output desired output, then an other line having None

Same with Aleksei Maide's answer.

Upvotes: 0

Aleksei Maide
Aleksei Maide

Reputation: 1855

You have nested for loops which gives you N^2 results, when you only want to do the operation once.

Every inner loop is run len(petalLength) times... Which compares every petalWidth to every petalLength instead of doing it in pairs.

def decision(petalLength, petalWidth):
    for i in range(len(petalLength)):
        if petalLength[i] < 4.8 and petalWidth[i] < 1.8:
            print("Versicolour")
        else:
            print("Virginica")

Upvotes: 0

user2390182
user2390182

Reputation: 73450

I assume what you want is pair-wise iteration, which you would generally do with zip:

for x, y in zip(petalLength, petalWidth):
    if x < 4.8 and y < 1.8:
        print("Versicolour")
    else:
        print("Virginica")

Upvotes: 1

Related Questions