详解pandas.str.endswith()(检测字符串结尾)函数使用方法

yizhihongxing

pandas.str.endswith() 是 pandas 库中的一个字符串方法,可以用来判断 DataFrame 或 Series 中的每一个字符串是否以某个字符或字符串结尾,返回一个 bool 类型的 Series。

使用方法

pandas.Series.str.endswith(self, pat, na=None, case=True)

参数说明

  • pat: 要判断的字符或字符串。可以是单个字符、字符串、元组、列表等。
  • na: 可选,replace方法中的na选项。
  • case: 是否区分大小写,默认 True,不区分大小写。

示例一:判断 DataFrame 中的字符串是否以某个字符结尾

import pandas as pd

data = {"Name": ["Tom", "Billy", "Jefferson", "Andrew", "Wesley", "Steven"],
        "Age": [25, 32, 18, 47, 23, 35],
        "City": ["Beijing", "Shanghai", "Guangzhou", "Shenzhen", "Hangzhou", "Chengdu"],
        "Email": ["tom@haha.com", "billy@haha.com", "jefferson@haha.com", "andrew@haha.com", "wesley@haha.com", "steven@haha.com"]}

df = pd.DataFrame(data)

# 判断 Email 列中是否以 .com 结尾,返回 bool 类型的 Series
df["Email"].str.endswith(".com")

输出结果:

0     True
1     True
2     True
3     True
4     True
5     True
Name: Email, dtype: bool

示例二:判断 Series 中的字符串是否以给定的字符或字符串结尾

import pandas as pd

s = pd.Series(["abc", "abcd", "xyz", "wxyz", "sdfg", "dfgh", "abc1", "acb2"])

# 判断每个字符串是否以 b, c, 1, 2 结尾,返回 bool 类型的 Series
s.str.endswith(("b", "c", "1", "2"))

输出结果:

0     True
1     True
2    False
3     True
4    False
5    False
6     True
7     True
dtype: bool

总结

pandas.str.endswith() 方法适用于 DataFrame 中特定列或 Series 中所有字符串的结尾匹配,可以通过传递不同的参数进行不同的结尾匹配,例如单个字符、字符串、元组、列表等。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:详解pandas.str.endswith()(检测字符串结尾)函数使用方法 - Python技术站

(6)
上一篇 2023年3月22日
下一篇 2023年3月22日

相关文章

合作推广
合作推广
分享本页
返回顶部