Pandas Series.str.fullmatch() 方法



Pandas 中的 Series.str.fullmatch() 方法用于确定 Series 中的每个字符串是否完全匹配指定的正则表达式模式。

当您想要验证整个字符串是否符合给定的格式或模式时,此方法很有用。它等同于将 re.fullmatch() 应用于 Series 中的每个字符串。

语法

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

Series.str.fullmatch(pat, case=True, flags=0, na=None)

参数

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

  • pat - 表示要匹配的字符序列或正则表达式模式的字符串。

  • case - 布尔值,默认为 True。如果为 True,则匹配区分大小写。

  • flags - 可选整数,默认为 0。来自 re 模块的标志,例如 re.IGNORECASE,用于修改模式匹配行为。

  • na - 用于缺失值的可选标量值。如果未指定,则默认值取决于 Series 的数据类型。对于 object-dtype,使用 numpy.nan。对于 StringDtype,使用 pandas.NA。

返回值

Series.str.fullmatch() 方法返回一个包含布尔值的 Series 或 Index。每个布尔值指示 Series 中相应的字符串是否完全匹配给定的正则表达式模式。

示例 1

此示例演示如何检查 Series 中的每个字符串是否完全匹配有效电子邮件地址的正则表达式模式。

import pandas as pd

# Create a Series of strings
s = pd.Series(['user@example.com', 'user@domain', 'example.com', 'test@tutorialspoint.com'])

# Check if each string fully matches the pattern for an email address
result = s.str.fullmatch(r'\w+@\w+\.\w+')

print("Input Series:")
print(s)
print("\nFull Match Results:")
print(result)

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

Input Series:
0           user@example.com
1                user@domain
2                example.com
3    test@tutorialspoint.com
dtype: object

Full Match Results:
0     True
1    False
2    False
3     True
dtype: bool

输出显示,只有完全匹配电子邮件模式的字符串才会标记为 True

示例 2

此示例演示如何使用 Series.str.fullmatch() 方法检查每个字符串是否完全匹配格式为 'YYYY-MM-DD' 的日期的模式。

import pandas as pd

# Create a Series of strings
s = pd.Series(['2024-07-29', '2024-07-29 00:00:00', '2024-07-29T00:00:00', '07-29-2024'])

# Check if each string fully matches the date pattern
result = s.str.fullmatch(r'\d{4}-\d{2}-\d{2}')

print("Input Series:")
print(s)
print("\nFull Match Results:")
print(result)

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

Input Series:
0             2024-07-29
1    2024-07-29 00:00:00
2    2024-07-29T00:00:00
3             07-29-2024
dtype: object

Full Match Results:
0     True
1    False
2    False
3    False
dtype: bool

示例 3

此示例演示如何检查 DataFrame 列中的每个字符串是否完全匹配日期模式,同时处理缺失值。

import pandas as pd

# Create a DataFrame with date strings
df = pd.DataFrame({
    'date': ['2024-07-29', '2024-07-29 00:00:00', '2024-07-29', None]
})

# Check if each string fully matches the date pattern, treating NaNs as True
result = df['date'].str.fullmatch(r'\d{4}-\d{2}-\d{2}', na=True)

print("Input DataFrame:")
print(df)
print("\nFull Match Results:")
print(result)

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

Input DataFrame:
                  date
0           2024-07-29
1  2024-07-29 00:00:00
2           2024-07-29
3                 None

Full Match Results:
0     True
1    False
2     True
3     True
Name: date, dtype: bool

在这种情况下,由于 na=True 参数,NaN 值被视为 True,而其他字符串则根据模式进行匹配。

python_pandas_working_with_text_data.htm
广告

© . All rights reserved.