识别以标点符号开头的名字

Identify names starting with punctuation

要检查一行是否以标点符号开头,我在考虑使用string.punctuation和string.startswith。但是当我这样做时

df['start_with_punct']=df['name'].str.startswith(string.punctuation)

当名称实际上以标点符号开头时,我得到错误。

数据示例为

Name       
_faerrar_
!gfaherr_!£
nafjetes_

预期输出

Name            start_with_punct
_faerrar_           True
!gfaherr_!£         True
nafjetes_           False

我需要了解如何获得正确的输出,因为我还需要使用以大写字母开头的名称对其进行测试。

使用 tuple 将多个值传递给 Series.str.startswith:

df['start_with_punct']=df['Name'].str.startswith(tuple(string.punctuation))
print (df)
         Name  start_with_punct
0   _faerrar_              True
1  !gfaherr_!              True
2   nafjetes_             False

要测试第一个值是否为大写,请使用 Series.str.isupper 和索引 str[0]:

df['start_with_upper']=df['Name'].str[0].str.isupper()
print (df)
         Name  start_with_upper
0    Aaerrar_              True
1  dgfaherr_!             False
2   Nafjetes_              True

您也可以使用 str.match,因为默认情况下匹配锚定到字符串的开头:

import re
regex = '[%s]' % re.escape(string.punctuation)
df['start_with_punct'] = df['Name'].str.match(regex)

输出:

          Name  start_with_punct
0    _faerrar_              True
1  !gfaherr_!£              True
2    nafjetes_             False