【问题标题】:Regex , First Two character as Alphabetic Python正则表达式,前两个字符为字母 Python
【发布时间】:2017-11-26 23:49:47
【问题描述】:

我有一个作为 df 的数据框和一个作为 Column1 的列 如果 column1 值不适用,则返回 False,或检查列中元素的前 2 个字符是否应为字母,并返回 True 或 False

df['Column1'].apply(lambda x : False if x in ['Not Applicable'] else x[0:2] should be alphabetic)

如何在 lambda 函数的 else 部分检查前两个字符是否为字母?

【问题讨论】:

  • 您可以添加具有所需输出的样本吗?
  • 这里没有问题。
  • @VigneshwaranMarkandan 他想检查申请的 else 中 x 的前两个字符是否是字母
  • x[0:2].isalpha()
  • @Coldspeed 谢谢

标签: python regex pandas dataframe lambda


【解决方案1】:

此解决方案不需要正则表达式。如果要检查这两个字母是否为字母,请使用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,所以可以使用返回值的真实性。

【讨论】:

  • 如果我想在里面使用正则表达式该怎么办
  • @Shivpe_R 已编辑。
【解决方案2】:

我认为你需要numpy.wherestr.isalphaindexing with str

df = pd.DataFrame({'col1':['Not Applicable dds','*7df Not Applicable','sd ds', '#@( 444']})

df['a'] = np.where(df['col1'].str.contains('Not Applicable'), False,
                   df['col1'].str[:2].str.isalpha())
print (df)
                  col1      a
0   Not Applicable dds  False
1  *7df Not Applicable  False
2                sd ds   True
3              #@( 444  False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-22
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多