Pandas If String Bad Operand Errors
Pandas “bad operand” errors involving strings are usually fixed by applying &, |, or ~ to complete Boolean Series, not directly to string values, and by using .str.contains() to create those Boolean Series. A related error such as unsupported operand type(s) for +: 'str' and 'int' means text and numeric values are being combined without an explicit conversion. The key is to identify the operator in the traceback, build a valid mask or converted column, and then use that result for filtering or calculation.
| Symptom | Likely Cause | Direct Fix |
|---|---|---|
TypeError: unsupported operand type(s) for &: 'str' and 'str' |
& is being applied to text values rather than Boolean conditions. |
Put each comparison or .str.contains() call in parentheses, then join the resulting masks with &. |
TypeError: bad operand type for unary ~: 'str' |
~ is being applied to a string column before a comparison is evaluated. |
Negate the completed condition: ~(condition). |
ValueError: The truth value of a Series is ambiguous |
A full Series is being used directly in if, and, or, or not. |
Filter with .loc[mask], or reduce the mask with .any() or .all(). |
TypeError: unsupported operand type(s) for +: 'str' and 'int' |
Code is adding text to a number, or a numeric column was read as text. | Convert to numeric for arithmetic, or convert the number to pandas’ string dtype for labels. |
What a Pandas Bad Operand Error Means
Pandas works with whole columns at once. A comparison such as df["status"].eq("open") produces one True or False value per row, which is a Boolean Series called a mask.
The operators have specific jobs:
&means element-by-element “and.”|means element-by-element “or.”~means element-by-element “not.”==,.eq(),!=, and.ne()compare values..str.contains()checks whether text contains a substring or pattern.
The error happens when Python receives the wrong types for an operator. For example, this tries to combine two literal strings with &, which is not a valid text operation:
"open" & "urgent"
This instead creates two Boolean Series and combines them correctly:
mask = (
df["status"].eq("open")
& df["priority"].eq("urgent")
)
Pandas also requires parentheses around each condition. Without them, Python can evaluate |, &, or ~ before it evaluates your comparison.
How to Fix Pandas String Bad Operand Errors
Step 1: Identify the Values on Both Sides of the Operator
Read the relevant traceback line and find the operator named in the error: &, |, ~, +, or another symbol. Then inspect the involved columns before converting anything.
print(df[["status", "description"]].dtypes)
If your goal is to filter rows, each condition must return a Boolean Series. If your goal is arithmetic, the operands must be numeric. If your goal is to build a label, convert the number to text deliberately.
A common broken filter looks like this:
mask = df["status"] == "open" | df["status"] == "pending"
Because of operator precedence, Python can try to apply | to strings before making both comparisons.
Step 2: Build One Complete Boolean Mask
For an exact string match, use .eq() and decide how missing values should behave. This version treats missing values as non-matches:
mask = df["status"].eq("open").fillna(False)
For a substring match, use .str.contains(). In pandas’ Series.str.contains, case=True is the default, so matching is case-sensitive unless you set case=False. Its default regex=True also means pandas interprets the search text as a regular expression; use regex=False for a literal substring.
mask = df["description"].astype("string").str.contains(
"invoice",
case=False,
regex=False,
na=False,
)
The conversion to pandas’ nullable "string" dtype is appropriate when the column represents text but may contain missing values. It preserves missing values rather than turning them into literal strings such as "None" or "<NA>".
To require two conditions, wrap each completed condition in parentheses:
mask = (
df["status"].eq("open").fillna(False)
& df["description"].astype("string").str.contains(
"invoice",
case=False,
regex=False,
na=False,
)
)
Step 3: Filter or Reduce the Mask Instead of Putting It Directly in if
A mask has one value per row, so it cannot be used directly as a single if condition.
Use .loc[mask] to keep matching rows:
result = df.loc[mask].copy()
print(result)
Use .any() when your program needs one answer to “does at least one row match?”:
if mask.any():
print(df.loc[mask])
Use .all() only when every row must match:
if mask.all():
print("Every row matches.")
Do not use Python’s and, or, or not between Series. Those keywords require one scalar truth value. Use &, |, and ~ for element-by-element pandas conditions.
Fix Incorrect ~, &, and | Placement
The unary ~ operator must negate the completed Boolean condition, not the original text column.
This is wrong because ~ runs before ==:
mask = ~df["team"] == "red"
This is correct:
mask = ~(df["team"].eq("red").fillna(False))
The same rule applies to & and |. Build conditions first, then combine them.
mask = (
df["team"].eq("red").fillna(False)
| df["team"].eq("blue").fillna(False)
)
For more than two alternatives, .isin() is often clearer than chaining operators:
mask = df["team"].isin(["red", "blue"])
If you need to exclude values while also excluding missing rows, state that rule explicitly:
mask = (
df["team"].notna()
& ~df["team"].eq("red").fillna(False)
)
That keeps rows with a known team other than "red".
Handle Missing Values in String Filters
Missing values are a major source of confusing string-filter errors. The result of .str.contains() depends on the source Series dtype: pandas uses False by default for the "str" dtype, numpy.nan for an object dtype, and pandas.NA for nullable StringDtype.
For a nullable string column used for filtering, set na=False when missing rows should not match; this creates a definite Boolean mask instead of propagating an unknown missing value.
Do not test pd.NA directly in an if statement. Its truth value is unknown, so this fails:
if pd.NA:
print("Missing")
Do not compare missing values with == either. Check them with pd.isna() instead:
ser = df["description"].astype("string")
missing = pd.isna(ser)
print(ser.loc[missing])
When you need a filter that finds rows with missing text, use the missing-value mask directly:
missing_description_rows = df.loc[pd.isna(df["description"])]
print(missing_description_rows)
Match One or Two Text Fragments
Use .str.contains() for partial matches, not Python’s in operator on a Series. Python’s in checks Series index labels by default, not whether each column value contains your text.
For two required text fragments in a fixed order, use str.contains('str1.*str2').
text = df["notes"].astype("string")
ordered = text.str.contains('str1.*str2').fillna(False)
result = df.loc[ordered]
For two fragments that can appear in either order, use str.contains('str1.*str2|str2.*str1').
either_order = text.str.contains('str1.*str2|str2.*str1').fillna(False)
result = df.loc[either_order]
These are regular expressions, so use regex=False for literal search text containing characters such as ., +, ?, [, or (. For example, a filename with square brackets should normally be treated literally:
mask = df["filename"].astype("string").str.contains(
"report[final].csv",
regex=False,
na=False,
)
Fix Unsupported Operand Type Errors for Strings and Integers
The error below is not a filtering problem:
df["next_quantity"] = df["quantity"] + 1
It fails when df["quantity"] contains strings such as "12" instead of numeric values. If the column represents a quantity, price, ID used in arithmetic, or another number, convert it to a numeric dtype first.
quantity = pd.to_numeric(df["quantity"], errors="raise")
df["next_quantity"] = quantity + 1
Keep the conversion step separate from the arithmetic so invalid values can be handled deliberately before calculation.
If the intended result is text, such as a display label, convert the numeric value to pandas’ nullable string dtype instead:
df["display_id"] = "item-" + df["item_id"].astype("string")
Avoid converting every column to strings just to silence an error. A value such as "0012" may be an identifier that should remain text, while "12" in an inventory-count column should become numeric. The correct fix depends on what the data means.
Confirm the Filter Before Using It Elsewhere
Before you use a mask in a larger pipeline, verify that it aligns with the DataFrame and has no missing Boolean values.
assert mask.index.equals(df.index)
assert not mask.isna().any()
filtered = df.loc[mask]
Inspect a few matched source values, especially after changing case sensitivity, regex behavior, or missing-value handling:
print(filtered[["description"]].head())
Use this checklist before reusing a mask in a larger pipeline:
- Give Boolean Series names such as
mask,has_invoice, oris_open. - Parenthesize every comparison before combining it with
&or|. - Use
.loc[mask]for row filtering. - Use
.any()or.all()only when you truly need one Boolean result. - Choose whether missing text should match, fail, or be handled separately.
- Convert data types based on meaning, not merely to remove an exception.
Frequently Asked Questions
How Do I Check if a String Is in a Pandas Column?
For an exact match, use .eq() and reduce the result with .any().
has_boston = df["city"].eq("Boston").fillna(False).any()
For a partial, case-insensitive match, use .str.contains() with case=False, regex=False, and na=False.
has_york = df["city"].astype("string").str.contains(
"York",
case=False,
regex=False,
na=False,
).any()
How Do I Fix TypeError: Unsupported Operand Type(s) for str and int`?
Decide whether the value is supposed to be a number or text. Use pd.to_numeric() before arithmetic, or .astype("string") before concatenating a number into a label.
df["total"] = pd.to_numeric(df["amount"], errors="raise") + 1
df["label"] = "order-" + df["order_id"].astype("string")
How Do I Check if Two Strings Are Not Equal in Pandas?
Use .ne() for an element-by-element “not equal” comparison. If missing values should not count as different, require both values to be present.
both_present = df["left"].notna() & df["right"].notna()
different = both_present & df["left"].ne(df["right"])
For two ordinary Python string variables rather than pandas columns, use left != right.
What Does df.to_string() Do?
df.to_string() creates one printable text representation of the entire DataFrame. It is useful for output or logging, but it does not convert individual DataFrame columns into usable string dtypes for filtering or calculations.
print(df.to_string())
For column-level string operations, use a text column directly or convert that column with .astype("string"), then apply methods such as .str.contains().
