ValueError: The truth value of a Series is ambiguous
You used a whole pandas Series where Python expected a single True or False. Use & and | with parentheses for filters, and .any() or .all() in if statements.
Updated
The error
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
NumPy has the same complaint for arrays:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
What it means
Python's if, and, or and not need one single True or False. You gave them a whole column of them. Should a Series of [True, False, True] count as True? Pandas refuses to guess, and raises instead.
Why it happens
The most common trigger is combining filters with and instead of &:
df[df["age"] > 18 and df["city"] == "Pune"] # failsand is Python syntax and works only on single booleans. The element-wise operators for columns are &, | and ~.
The second trigger is testing a Series directly:
if df["age"] > 18: # fails: 10,000 answers, not one
...How to fix it
1. Combine filters with & and |, with parentheses around each condition. The parentheses are required — & binds tighter than >.
adults_in_pune = df[(df["age"] > 18) & (df["city"] == "Pune")]2. In an if, say which single answer you want.
if (df["age"] > 18).all(): # every row?
...
if (df["age"] > 18).any(): # at least one row?
...3. To check whether a filter found anything, test .empty.
matches = df[df["order_id"] == 1042]
if not matches.empty:
...4. If the Series should hold exactly one value, extract it.
price = df.loc[df["order_id"] == 1042, "price"].item().item() raises if there is not exactly one value, which is a useful safety check.
5. For if/else logic across a column, use np.where instead of if.
df["band"] = np.where(df["age"] > 18, "adult", "minor")How to prevent it
Read & as "and", | as "or", ~ as "not" whenever you work with columns, and always add the parentheses. Keep Python's and/or for single values only. When an if touches a Series, stop and ask: do I mean any, all, or exactly one?