详解pandas.Series.str.startswith()(检测序列中的字符串开头)函数使用方法

  • Post category:Python

pandas.Series.str.startswith() 是pandas中Series对象的一种字符串匹配函数,用于判断Series对象中各个字符串是否以指定前缀开头。具体来说,该函数可以将Series对象中的每个字符串与指定的前缀进行匹配,返回一个由布尔值组成的Series对象,表示每个字符串是否以指定的前缀开头。若以指定前缀开头则返回True,否则返回False。

使用方法如下:

Series.str.startswith(pat, na=False)

其中,pat表示指定的前缀字符串,na表示是否将series中的NA值视为True或False。

下面分别通过两个实例说明该函数的具体使用方法:

例1:假设我们有一个Series对象,其中存放了一些人的姓名信息。现在我们想获取其中以字母“A”开头的名字。可以使用str.startswith()函数如下:

import pandas as pd

# 创建一个Series对象
s = pd.Series(["Alice", "Bob", "Ada", "Ann"])
# 使用startswith函数匹配
result = s.str.startswith("A") 

print(result)

输出结果:

0     True
1    False
2     True
3     True
dtype: bool

可以看到,该函数返回了一个由布尔值组成的Series对象,表示每个字符串是否以”A”开头。

例2:假设我们有一个Series对象,其中存放了一些网站的URL信息。现在我们想获取其中以”http”或”https”开头的URL。可以使用str.startswith()函数如下:

import pandas as pd

# 创建一个Series对象
s = pd.Series(["http://www.sina.com.cn/", 
               "https://www.jd.com/", 
               "ftp://www.baidu.com/",
               "http://www.taobao.com/"])
# 使用startswith函数匹配
result = s.str.startswith(("http", "https")) 

print(result)

输出结果:

0     True
1     True
2    False
3     True
dtype: bool

可以看到,该函数支持传入一个元组进行多个前缀的匹配,返回了一个由布尔值组成的Series对象。