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. The result is True and False(Boolean).
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. I don't know how to match if condition with a regex. It seems the value of Name which is True/ False hasn't been checked in the if condition.
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
.
If you want to allow any amount of leading whitespace chars, you may also add \\s*
after ^
and use 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.