Tom2shoes
Tom2shoes

Reputation: 125

Why doesn't this while loop break when iterating through pandas dataframe?

When I run the code it seems to iterate through the whole dataframe twice and it ignores the while condition

import pandas as pd

a = 0

sales = [
         {'account': 'Jones LLC', 'Jan': 150, 'Feb': 200, 'Mar': 140},
         {'account': 'Alpha Co',  'Jan': 200, 'Feb': 210, 'Mar': 215},
         {'account': 'Blue Inc',  'Jan': 50,  'Feb': 90,  'Mar': 95 },
         {'account': 'Blue Inc',  'Jan': 50,  'Feb': 90,  'Mar': 95 },
         {'account': 'Blue Inc',  'Jan': 50,  'Feb': 90,  'Mar': 95 },
         {'account': 'Blue Inc',  'Jan': 50,  'Feb': 90,  'Mar': 95 }
        ]

df = pd.DataFrame(sales)

while a <= 6:
    for index, row in df.iterrows():
        df.loc[index, 'a'] = a
        print(a, index)
        a += 1

df

Upvotes: 1

Views: 3225

Answers (2)

ansev
ansev

Reputation: 30930

Use:

a=0
for index, row in df.iterrows():
    df.loc[index, 'a'] = a
    print(a, index)
    a += 1

While loop is not necessary, because for stop when there aren't more dict in the list. If you would want use while loop you should use <6 instead , not <=6 because when for finally a=6 and then the for loop would run again.

Upvotes: 1

jottbe
jottbe

Reputation: 4521

I guess what you want is, that the assignemt stops after the 6th row, right?

That would be

a= 0
for index, row in df.iterrows():
    df.loc[index, 'a'] = a
    print(a, index)
    a += 1
    if a == 6:
        break

The while loop indeed has an effect in your case. The loop body is executed twice, which explains the values 6...11 in column a. In the first iteration of the while loop a is zero, so it enteres the loop. As the inner loop has no restriction, it just loops over all records, increasing a in each iteration. If you have exactly 6 records in your df, it exits with a==6 which means, that the while loop is iterated once more. Then finally a == 12 and it terminates leaving your dataframe with values 6 ... 11 in column a, which are the values set by the second iteration of the while loop.

Upvotes: 2

Related Questions