计算熊猫数据框中的左括号

时间:2021-05-25 09:14:34

标签: python pandas string parentheses

我正在尝试在数据帧列中使用 python 中的 string.punctuation 模块计算符号数,但我找不到一种方法来计算左括号,因为 python 认为它显然不认为它是一个字符串。< /p>

我正在研究 linux + Jupyter notebook 和 python 3.8。

df = pd.DataFrame()
df['password'] = data
df['sign'] = 0
for i in string.punctuation:
    print(i)
    print(type(i))
    df['sign'] += df['password'].str.count(i)
    
df['sign'].iloc[:100]

这给了我:

!
<class 'str'>
"
<class 'str'>
#
<class 'str'>
$
<class 'str'>
%
<class 'str'>
&
<class 'str'>
'
<class 'str'>
(
<class 'str'>

然后是异常:

/opt/conda/lib/python3.8/sre_parse.py in _parse(source, state, verbose, nested, first)
    834             p = _parse_sub(source, state, sub_verbose, nested + 1)
    835             if not source.match(")"):
--> 836                 raise source.error("missing ), unterminated subpattern",
    837                                    source.tell() - start)
    838             if group is not None:

error: missing ), unterminated subpattern at position 0

谢谢。

2 个答案:

答案 0 :(得分:3)

示例数据框:

df = pd.DataFrame({'text': ['hel\\l\'o', 'hellO()world']})

括号是正则表达式语法的一部分,因此您需要对它们进行转义:

df['text'].str.count('\(')

要涵盖所有 string.punctuation,您可以使用:

df['text'].str.count(f'[{re.escape(string.punctuation)}]')

答案 1 :(得分:0)

我用过这个,如果有人来这里也能用:

count = lambda l1,l2: sum([1 for x in l1 if x in l2])
df['punctuation'] = df['password'].apply(lambda s: count(s, string.punctuation))