kevin python
kevin python

Reputation: 5

python nested loop "if" statement

import pandas as pd

Data = {'participant': ['Jordan', 'Jess', 'Jake', 'Alice', 'Alan', 'Lauren'], 'Age': [26, 23, 19, 20, 24, 28], 'Sex': ['M', 'F', 'M', 'F', 'M', 'F'], 'BMI': [26, 22, 24, 17, 35, 20], 'Smokes': ['No', 'No', 'Yes', 'No', 'Yes', 'No']}
df = pd.DataFrame(Data)
print(df)
for name in 'participant':
  for ages in 'Age':
    for sexs in 'Sex':
      for Bmis in 'BMI':
        for smoke in 'Smokes':
          if nmb.find(str(30)) >= 30:
            print('participant')
  else: 
    print('none found')

question: What line of code would bring down the participants name that has a BMI of 30 or higher? How would i implant that?

Upvotes: 0

Views: 53

Answers (2)

adhg
adhg

Reputation: 10863

You asked for the participants names so simply do:

df[df['BMI']>=30][['participant']]

will do the trick. Result:

    participant   
4          Alan   

If you wish to have the result as an array: df[df['BMI']>=30][['participant']].values

As a side note: when you code and have nested for loops with many if statements - you're (very very likely) doing something wrong. Use it as a signal to come with a different (elegant) strategy.

Upvotes: 0

yatu
yatu

Reputation: 88236

You should read on what the purpose of looping is, since this will definitely not do what you want. Also check Indexing and selecting data, which is what you should be doing here.

For what you want, you'd just need:

df.Age.ge(30).sum()

Upvotes: 4

Related Questions