panda与Python中匹配字符串(REGEX)中的If条件

2024-04-25 17:43:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想在正则表达式匹配之前添加一个if条件: 首先我定义正则表达式并将值存储在Name中,然后打印Name值。结果为True和False(布尔值)

Name = df['Name'].str.match('^(\w+\s*)$')
#If the result matches True value passed and else the value will be False
print(Name) 

结果

:
True
False
True

下面的代码是关于我的if条件。我不知道如何将if条件与正则表达式匹配。 似乎在if条件中没有检查Name的值True/False

if Name is True:
     print(Name)
else:
     print('bye')

代码结果:

bye

预期结果:

John
Saher

谢谢


Tags: the代码namefalsetruedfif定义
1条回答
网友
1楼 · 发布于 2024-04-25 17:43:54

你可以用

df.loc[df['Name'].str.match(r'^\w+\s*$')]

注意:您不需要将带有正则表达式的捕获组作为参数传递给Series.str.match,它只在extract/extractall中需要

如果要允许任何数量的前导空格字符,还可以在^之后添加\s*并使用r'^\s*\w+\s*$'

熊猫测试:

import pandas as pd
df = pd.DataFrame({'Name': ['John', ' -', 'Saher']})
>>> df.loc[df['Name'].str.match('^(\w+\s*)$')]
    Name
0   John
2  Saher

相关问题 更多 >