Home > Software design >  How to break a current loop and go to the next loop when a condition is meet in python?
How to break a current loop and go to the next loop when a condition is meet in python?

Time:12-13

I have a data frame like below. Now I want to iterate through unique values of column Name and get the values of column Age when the Age is 10 and when the condition is meet the loop has to break and continue with the next loop. I tried to break it using while loop but it is not working. What is the best way to loop which can break the current loop once the condition is meet and go to the next loop?

Data Frame:-
import pandas as pd
data = [['tom', 10], ['nick', 5], ['juli', 4],
       ['tom', 11], ['nick', 7], ['juli', 24],
       ['tom', 12], ['nick', 10], ['juli', 15],
       ['tom', 14], ['nick', 20], ['juli', 17]]
df = pd.DataFrame(data, columns=['Name', 'Age'])
Loop:-

    for j in df['Name'].unique():
        print(j)
        o=0
        t=[]
        while o == 10:
            for k in df['Age']:
                if k == 10:
                    t.append(k)
                    o = k

output:-
tom
nick
juli

It it printing the values in column Name but not printing the values inside the while loop. How do I achieve it?

CodePudding user response:

Do you mean something like this?

# Data Frame:-
import pandas as pd
data = [['tom', 10], ['nick', 5], ['juli', 4],
       ['tom', 11], ['nick', 7], ['juli', 24],
       ['tom', 12], ['nick', 10], ['juli', 15],
       ['tom', 14], ['nick', 20], ['juli', 17]]
df = pd.DataFrame(data, columns=['Name', 'Age'])

# Loop:-
for j in df['Name'].unique():
    print("Name:", j)
    for i in df[df['Name']==j]['Age']:
        print("Age:", i)
        if i == 10:
            print("Found age 10 for", j)
            break

CodePudding user response:

You can do something like this -

for name in df['Name'].unique():
  matching_ages = []

  # loop through age
  for age in df['Age']:
    if age == 10:
      matching_ages.append(age)
      break

  # print the output
  print(name, matching_ages)

This will return the output like this - Output

  • Related