Home > Blockchain >  How to solve this ? how to handling my mistake to stop loop
How to solve this ? how to handling my mistake to stop loop

Time:07-07

this my data :

data = {
    'Customer_ID':['CUS_0xd40','CUS_0xd40','CUS_0xd40', 'CUS_0x21b1', 'CUS_0x2dbc'],
    'SNN': ['821-00-0265','#F%$D@*&8','004-07-5839','133-16-7738', '031-35-0942'],
    'Occupation':['Scientist', '_______' ,'Scientist', 'Engineer' ,'Entrepreneur'], 
    'Credit_Mix':['_', 'Good', 'Standard','Bad', 'Standard']  
}

df=pd.DataFrame(data)

I wrote this code but the code has infinite loop how to solve this?? the aim is comparing according to Customer_ID in row( i) androw( i 1) if it the same, this lead to change Credit_Mix and Occupation with same value in next row(i 1)

  for i, row in df.iterrows():
        
        while i <=4:
            if df.loc[i, "Customer_ID"] == df.loc[i 1, "Customer_ID"]:
                if row["Credit_Mix"] == '_':
                    df.loc[i, "Credit_Mix"] = df.loc[i 1, "Credit_Mix"]
                else:
                    df.loc[i, "Credit_Mix"] = df.loc[i, "Credit_Mix"]
            
                if row["Occupation"] == '_______':
                    df.loc[i, "Occupation"] = df.loc[i 1, "Occupation"]
                else:
                    df.loc[i, "Occupation"] = df.loc[i, "Occupation"]
            
            else:
                 pass

CodePudding user response:

You are looping over i in the for loop, and in the case i is less than or equal to 4 you are running a while loop.

for i in range(5):
    print(i)

This code loops over a range of numbers from 0 to 4, the output of the above code will look like this:

0
1
2
3
4
for i in range(5):
    print(i)
    while i == 2:
        print("i is 2")

This code does the same, it loops over a range of numbers, from 0 to 4, but when i becomes 2 a while loop starts informing us that i is equal to 2, but i is never incremented so i will stay equal to 2. The output of the above code will look like this:

0
1
2
i is 2
i is 2
i is 2
   .
   .
   .

...and so on, never ending.

CodePudding user response:

I think your problem is equivalent with this code.

def do_something():
    print('do something')

for i, row in enumerate(['a', 'b', 'c', 'd']):
    while i <= 4:
        do_something()

The condition i <= 4 will always be true, try to change your code flow so this condition can be false.

  • Related