0

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

4
  • 1
    You have not asked any questions, but judging by the story, you need df.loc[Name,'Name']. Commented Nov 16, 2020 at 7:03
  • Dear DYZ , I update my content. You are right and I appreciate the time you spend. I am new with python and panda. my question relates to if condition. Now where I have to add df.loc? Commented Nov 16, 2020 at 7:07
  • Just print it, and your text is still not a question. Commented Nov 16, 2020 at 7:08
  • My problem is about if condition not printing the value. Commented Nov 16, 2020 at 7:13

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.