﻿ Pandas DataFrame: Select the rows where number of attempts in the examination is less than 2 and score greater than 15 - w3resource

# Pandas DataFrame: Select the rows where number of attempts in the examination is less than 2 and score greater than 15

## Pandas: DataFrame Exercise-11 with Solution

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

Sample DataFrame:
Sample Python dictionary data and list labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Sample Solution :

Python Code :

``````import pandas as pd
import numpy as np
exam_data  = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print("Number of attempts in the examination is less than 2 and score greater than 15 :")
print(df[(df['attempts'] < 2) & (df['score'] > 15)])
``````

Sample Output:

```Number of attempts in the examination is less than 2 and score greater than 15 :
name  score  attempts qualify
j  Jonas   19.0         1     yes
```

Explanation:

The above code first creates a Pandas DataFrame ‘df’ using the dictionary ‘exam_data’ and a list labels. It then selects the rows where the number of attempts is less than 2 and the score is greater than 15 using the & operator for and condition. Finally, it prints the selected rows of the DataFrame.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿