我有一个 Dataframe 作为 df 和 Column 作为 Column1 如果 column1 的值为 Not Applicable,则返回 False,或者检查列中元素的前 2 个字符是否应为字母,并返回 True 或 False
df['Column1'].apply(lambda x : False if x in ['Not Applicable'] else x[0:2] should be alphabetic)
如何在 lambda 函数的 else 部分检查前两个字符是字母?
最佳答案
此解决方案不需要正则表达式。如果你想检查这 2 个字母是字母表,使用 str.isalpha()
功能。
df['Column1'].apply(lambda x : False if x in ['Not Applicable'] else x[0:2].isalpha())
应 OP 的要求,使用 re.match
:
import re
df['Column1'].apply(lambda x : False if x in ['Not Applicable'] else re.match('[a-z]{2}', x[0:2].lower()) )
re.match
如果匹配则返回匹配对象,否则返回None
,所以可以利用返回值的真实性。
关于python - 正则表达式,前两个字符作为字母 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44720741/