Vectorized Conditions Gone Wrong
A vectorized Pandas discount calculation fails because of a Python-vs-NumPy logical operator mistake.
Codepython
import numpy as np
import pandas as pd
df = pd.DataFrame({'price': [100, 200, 300], 'qty': [1, 5, 2]})
# Goal: 10% discount when price > 150 AND qty >= 2, else 0%
df['discount'] = np.where(
(df['price'] > 150) and (df['qty'] >= 2),
0.10,
0.00,
)
print(df)This code raises 'ValueError: The truth value of a Series is ambiguous'. What is the bug and how do you fix it?