Pandas Series.str.endswith() Method



The Series.str.endswith() method in Pandas is used to test if the end of each string element in a Series or Index matches a specified pattern. This method is useful for filtering and analyzing text data based on suffix patterns.

This method is similar to the str.endswith() method in Python, providing an easy way to handle pattern matching at the end of strings within a Pandas Series or Index.

Syntax

Following is the syntax of the Pandas Series.str.endswith() method −

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

Parameters

The Series.str.endswith() method accepts the following parameters −

  • pat − A string or tuple of strings representing the character sequence(s) to test for at the end of each element.

  • na − An optional object to show if the element tested is not a string. The default depends on the dtype of the array. For object-dtype, numpy.nan is used. For StringDtype, pandas.NA is used.

Return Value

The Series.str.endswith() method returns a Series or Index of booleans indicating whether the given pattern matches the end of each string element.

Example 1

In this example, we demonstrate the basic usage of the Series.str.endswith() method by testing if the strings in a Series end with the character 't'.

import pandas as pd
import numpy as np

# Create a Series of strings
s = pd.Series(['Python', 'Tutorialspoint', 'caT', np.nan])

# Test if strings end with 't'
result = s.str.endswith('t')

print("Input Series:")
print(s)
print("\nSeries after calling str.endswith('t'):")
print(result)

When we run the above code, it produces the following output −

Input Series:
0           Python
1    Tutorialspoint
2              caT
3              NaN
dtype: object

Series after calling str.endswith('t'):
0    False
1     True
2    False
3      NaN
dtype: object

Example 2

This example demonstrates how to use the Series.str.endswith() method to test if strings in a Series end with either 'n' or 'T'.

import pandas as pd
import numpy as np

# Create a Series of strings
s = pd.Series(['Python', 'Tutorialspoint', 'caT', np.nan])

# Test if strings end with 'n' or 'T'
result = s.str.endswith(('n', 'T'))

print("Input Series:")
print(s)
print("\nSeries after calling str.endswith(('n', 'T')):")
print(result)

Following is the output of the above code −

Input Series:
0           Python
1    Tutorialspoint
2              caT
3              NaN
dtype: object

Series after calling str.endswith(('n', 'T')):
0     True
1    False
2     True
3      NaN
dtype: object

Example 3

The Series.str.endswith() method can also be applied to a DataFrame to check whether each element in a specified column ends with a given string or characters. The method returns a boolean Series object.

import pandas as pd

# Creating a DataFrame for employees
employee_df = pd.DataFrame({
    'Employee_ID': ['E101', 'E102', 'E103', 'E104', 'E105'],
    'Name': ['John', 'Emily', 'Mark', 'Sarah', 'Jessica'],
    'Department': ['Sales', 'HR', 'IT', 'Marketing', 'Finance'],
    'Salary': [50000, 60000, 75000, 80000, 90000]
})

# Check if 'Name' column values end with 'h'
result = employee_df['Name'].str.endswith('h')

print("Printing Original Employee DataFrame:")
print(employee_df)
print("\nBoolean Series after calling str.endswith('h') on 'Name' column:")
print(result)

Following is the output of the above code −

Printing Original Employee DataFrame:
  Employee_ID     Name Department  Salary
0        E101     John      Sales   50000
1        E102    Emily         HR   60000
2        E103     Mark         IT   75000
3        E104    Sarah  Marketing   80000
4        E105  Jessica    Finance   90000

Boolean Series after calling str.endswith('h') on 'Name' column:
0     True
1    False
2    False
3     True
4    False
Name: Name, dtype: bool
python_pandas_working_with_text_data.htm
Advertisements