0
0
Pandasdata~20 mins

eval() for expression evaluation in Pandas - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Eval Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1:30remaining
Output of pandas.eval() with arithmetic expression
What is the output of the following code snippet using pandas.eval()?
Pandas
import pandas as pd
result = pd.eval('3 + 4 * 2')
print(result)
ASyntaxError
B14
C10
D11
Attempts:
2 left
💡 Hint
Remember the order of operations: multiplication before addition.
data_output
intermediate
2:00remaining
Evaluating a boolean expression on a DataFrame
Given the DataFrame df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}), what is the output of pd.eval('df.A > 1 & df.B < 6')?
Pandas
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
result = pd.eval('df.A > 1 & df.B < 6')
print(result)
A[False, True, False]
B[False, True, True]
C[True, False, False]
DSyntaxError
Attempts:
2 left
💡 Hint
Check each row: is A > 1 and B < 6 both true?
🔧 Debug
advanced
1:30remaining
Identify the error in pandas.eval() expression
What error does the following code raise?
import pandas as pd
df = pd.DataFrame({'x': [1, 2], 'y': [3, 4]})
pd.eval('df.x + df.z')
Pandas
import pandas as pd
df = pd.DataFrame({'x': [1, 2], 'y': [3, 4]})
pd.eval('df.x + df.z')
AKeyError: 'z'
BNameError: name 'df' is not defined
CSyntaxError
DTypeError
Attempts:
2 left
💡 Hint
Check if all columns used in the expression exist in the DataFrame.
🚀 Application
advanced
2:00remaining
Using pandas.eval() to filter rows efficiently
You want to filter rows in DataFrame df where column 'score' is greater than 50 and 'age' is less than 30. Which code using pandas.eval() produces the correct filtered DataFrame?
Pandas
import pandas as pd
df = pd.DataFrame({'score': [45, 60, 70], 'age': [25, 35, 28]})
Afiltered = df[pd.eval('score > 50 and age < 30')]
Bfiltered = df[pd.eval('score > 50 & age < 30')]
Cfiltered = df[pd.eval('df.score > 50 & df.age < 30')]
Dfiltered = df[pd.eval('df.score > 50 and df.age < 30')]
Attempts:
2 left
💡 Hint
Use the 'df.' prefix for column names when not passing target=df to pd.eval(). Use bitwise '&' for element-wise logical operations.
🧠 Conceptual
expert
1:30remaining
Understanding the scope of variables in pandas.eval()
Consider the code below. What will be the output of pd.eval('a + b')?
import pandas as pd
a = 5
b = 10
result = pd.eval('a + b')
print(result)
Pandas
import pandas as pd
a = 5
b = 10
result = pd.eval('a + b')
print(result)
ANameError: name 'a' is not defined
B15
CTypeError
DSyntaxError
Attempts:
2 left
💡 Hint
pandas.eval() can access variables from the local Python environment.