Bird
Raised Fist0
PandasHow-ToBeginner · 3 min read

How to Use str.endswith in pandas for String Filtering

Use Series.str.endswith() in pandas to check if each string in a column ends with a specified suffix. It returns a boolean Series that you can use to filter rows or analyze data.
📐

Syntax

The basic syntax of str.endswith() in pandas is:

  • Series.str.endswith(pat, na=None)

Where:

  • pat is the suffix string or tuple of suffixes to check.
  • na defines the boolean value to use for missing values (default is None).
python
Series.str.endswith(pat, na=None)
💻

Example

This example shows how to use str.endswith() to filter a pandas DataFrame for rows where a column's string ends with '.com'.

python
import pandas as pd

data = {'email': ['alice@example.com', 'bob@test.org', 'carol@example.com', 'dave@work.net']}
df = pd.DataFrame(data)

# Check which emails end with '.com'
ends_with_com = df['email'].str.endswith('.com')

# Filter rows where email ends with '.com'
filtered_df = df[ends_with_com]

print(ends_with_com)
print(filtered_df)
Output
0 True 1 False 2 True 3 False Name: email, dtype: bool email 0 alice@example.com 2 carol@example.com
⚠️

Common Pitfalls

Common mistakes when using str.endswith() include:

  • Passing a list instead of a string or tuple as the suffix.
  • Not handling missing values, which can cause unexpected NaN results.
  • Using it on non-string columns without converting them first.

Always ensure the column is string type and handle na parameter if needed.

python
import pandas as pd

data = {'values': ['apple', None, 'banana', 123]}
df = pd.DataFrame(data)

# Wrong: will raise error or unexpected results
# df['values'].str.endswith(['e', 'a'])  # list instead of string or tuple

# Right: use tuple for multiple suffixes and handle na
result = df['values'].astype(str).str.endswith(('e', 'a'), na=False)
print(result)
Output
0 True 1 False 2 True 3 False Name: values, dtype: bool
📊

Quick Reference

ParameterDescription
patString or tuple of suffixes to check for
naBoolean value to use for missing data (default None)
ReturnsBoolean Series indicating if each string ends with suffix
✅

Key Takeaways

Use Series.str.endswith() to check if strings in a pandas column end with a specific suffix.
Pass a string or tuple of strings as the suffix; do not use a list.
Handle missing values with the na parameter to avoid unexpected results.
Convert non-string columns to string before using str.endswith to prevent errors.
The method returns a boolean Series useful for filtering or analysis.