简体   繁体   English

如果在使用 Python 的熊猫中匹配字符串(REGEX)中的条件

[英]If condition in matching strings(REGEX) in panda with Python

I just want to add a if condition before a regex matching: first I define the regex and store the values in Name, then I print the Name value.我只想在正则表达式匹配之前添加一个 if 条件:首先我定义正则表达式并将值存储在 Name 中,然后我打印 Name 值。 The result is True and False(Boolean).结果是 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) 

Result结果

:
True
False
True

The below code is about the if condition I have.下面的代码是关于我拥有的 if 条件。 I don't know how to match if condition with a regex.我不知道如何将 if 条件与正则表达式匹配。 It seems the value of Name which is True/ False hasn't been checked in the if condition.似乎没有在 if 条件中检查 Name 的值为 True/False 的值。

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

Code Result:代码结果:

bye

Expected Result:预期结果:

John
Saher

Thanks谢谢

You can use您可以使用

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

Note you do not need the capturing group with a regex passed as an argument to Series.str.match , it is only required in extract / extractall .注意:你不需要与作为参数传递给正则表达式捕获组Series.str.match ,只需要extract / extractall

If you want to allow any amount of leading whitespace chars, you may also add \\s* after ^ and use r'^\\s*\\w+\\s*$' .如果您想允许任何数量的前导空白字符,您还可以在^之后添加\\s*并使用r'^\\s*\\w+\\s*$'

Pandas test:熊猫测试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM