elizac
elizac

Reputation: 11

Simplifying elif

I've got a bunch of elif functions:

 if 0 <= A.iloc[Row] <= 5:
        B = C.iloc[0,0]
    
    elif 5 <= A.iloc[Row] <= 10:
        B = C.iloc[1,0]
    
    elif 10 <= A.iloc[Row] <= 15:
        B = C.iloc[2,0]
    
    elif 15 <= A.iloc[Row] <= 20:
        B = C.iloc[3,0]
...

Is there a way to simplify my elif functions so they iterate through up to a 95<x<100?

I thought about using a while loop, but I can't seem to figure it out. (I'm only in the very beginner stages of learning Python).

Upvotes: 0

Views: 78

Answers (3)

Adon Bilivit
Adon Bilivit

Reputation: 26993

The logic in the question seems to be flawed due to overlaps.

If we assume that B = C.iloc[0,0] when 0 <= A.iloc[Row] < 5 then all you need is:

B = C.iloc[A.iloc[Row]//5, 0]

Upvotes: 0

Miles
Miles

Reputation: 399

With a while loop it would look like this:

a = 0
while a <= 100:
    if a <= A.iloc[Row] <= a+5:
        B = C.iloc[0,0]
    a += 5

Upvotes: 0

azro
azro

Reputation: 54148

You could use a for loop

for i in range(0, 100, 5):
    if i <= A.iloc[Row] < i + 5:
        B = C.iloc[i // 5, 0]

Or math

chunk = A.iloc[Row] // 5
B = C.iloc[chunk, 0]

Note that <= A.iloc[Row] <= is not very correct regarding the logic, should be <= A.iloc[Row] < because a bound shouldn't be in 2 cases

Upvotes: 1

Related Questions