Selecting Rows Based on Multiple Conditions

Write a Pandas program to select the rows where the number of attempts in the examination is less than 2 and the score is greater than 15.

Example 1:

Input: DataFrame with 'attempts' and 'score' columns 
Output: Rows where 'attempts' < 2 and 'score' > 15

Example 2:

Input: DataFrame with 'attempts' and 'score' columns 
Output: Rows where 'attempts' < 2 and 'score' > 15

Use pandas DataFrame conditional selection with logical operators.

import pandas as pd

def select_rows(df):
    return df[(df['attempts'] < 2) & (df['score'] > 15)]

df1 = pd.DataFrame({'name': ['Tom', 'Jack', 'Steve', 'Ricky'], 'score': [18, 19, 20, 21], 'attempts': [1, 2, 1, 2]})
df2 = pd.DataFrame({'name': ['Adam', 'Eve', 'Stark', 'Rogers'], 'score': [16, 15, 16, 17], 'attempts': [1, 1, 2, 2]})

print(select_rows(df1))
print(select_rows(df2))

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!