Pandas: Contains Using Case Insensitive Search
To perform case-insensitive string matching in Pandas, you can use the .str
accessor along with regular expressions and the case=False
parameter
(1) parameter case of str.contains
df1['col'].str.contains("MaX", na=False, case=False)
(2) Margin only on columns
df.query("City.str.lower() == 'new york'")
(3) Margin only on columns
df[df['col'].str.strip().str.match('MaX'.strip(), case=False)]
1. Check if a string contains a word (case-insensitive)
import pandas as pd
df = pd.DataFrame({
'name': ['maximum', 'Maxxy', 'MAXa', 'Mini', 'MInimum', 'MaX']
})
# Filter rows where 'name' contains 'bob', ignoring case
filtered = df[df['name'].str.contains('max', case=False)]
print(filtered)
Output:
name
0 maximum
1 Maxxy
2 MAXa
5 MaX
2. Exact match ignoring case
For exact matches (not substrings), normalize strings using .str.lower()
or .str.upper()
:
df[df['name'].str.lower() == 'max']
Result:
name
5 MaX
3. Case-insensitive query
We can perform case-insensitive search with Pandas query like:
df.query("name.str.lower() == 'max'")
Result:
name
5 MaX
Notes:
case=False
works only with.str.contains()
and.str.match()
using regex.- For non-regex comparisons, normalize both sides with
.str.lower()
or.str.upper()
.
Summary
To make your string filters case-insensitive in Pandas:
- Use
.str.contains(..., case=False)
for substring matching. - Use
.str.lower()
or.str.upper()
for exact value comparisons.