Pandas Series.str.endswith() 方法



Pandas 中的Series.str.endswith()方法用于测试 Series 或索引中每个字符串元素的末尾是否与指定的模式匹配。此方法对于根据后缀模式过滤和分析文本数据很有用。

此方法类似于 Python 中的str.endswith()方法,提供了一种简单的方法来处理 Pandas Series 或索引中字符串末尾的模式匹配。

语法

以下是 Pandas Series.str.endswith()方法的语法:

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

参数

Series.str.endswith()方法接受以下参数:

  • pat - 表示要测试每个元素末尾的字符序列的字符串或字符串元组。

  • na - 一个可选对象,用于显示被测试的元素是否不是字符串。默认值取决于数组的数据类型。对于对象数据类型,使用numpy.nan。对于StringDtype,使用pandas.NA

返回值

Series.str.endswith()方法返回一个 Series 或索引,其中包含布尔值,指示给定模式是否与每个字符串元素的末尾匹配。

示例 1

在本例中,我们演示了Series.str.endswith()方法的基本用法,通过测试 Series 中的字符串是否以字符“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)

当我们运行上述代码时,它会产生以下输出:

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

示例 2

此示例演示了如何使用Series.str.endswith()方法来测试 Series 中的字符串是否以“n”或“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)

以下是上述代码的输出:

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

示例 3

Series.str.endswith()方法也可以应用于 DataFrame,以检查指定列中的每个元素是否以给定的字符串或字符结尾。该方法返回一个布尔 Series 对象。

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)

以下是上述代码的输出:

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
广告

© . All rights reserved.