计算数据帧中的左括号 我试图用数据流列中的Python中的String。标点符号来计算符号数,但是我找不到一种方法来计算圆括号,因为Python认为它显然不考虑字符串。

计算数据帧中的左括号 我试图用数据流列中的Python中的String。标点符号来计算符号数,但是我找不到一种方法来计算圆括号,因为Python认为它显然不考虑字符串。,python,pandas,string,parentheses,Python,Pandas,String,Parentheses,我正在使用linux+Jupyter笔记本和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'&g

我正在使用linux+Jupyter笔记本和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'>
谢谢。

数据帧示例:

df=pd.DataFrame({'text':['hel\\l'o','hellO()world']})
括号是正则表达式语法的一部分,因此需要对其进行转义:

df['text'].str.count('\('))
要覆盖所有
字符串.标点符号
,您可以使用:

df['text'].str.count(f'[{re.escape(string.标点符号)}]]
数据帧示例:

df=pd.DataFrame({'text':['hel\\l'o','hellO()world']})
括号是正则表达式语法的一部分,因此需要对其进行转义:

df['text'].str.count('\('))
要覆盖所有
字符串.标点符号
,您可以使用:

df['text'].str.count(f'[{re.escape(string.标点符号)}]]

我用过这个,如果有人来到这里,它也会起作用:

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))

我用过这个,如果有人到了这里,它也会起作用:

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))

将模式括在
[]
中是个好主意+1为什么用括号括起来[{?要在f字符串中使用变量,请将它们用大括号括起来,例如
print(f“2+2等于{2+2}!”)
至于方括号
count(“abc”)
将在
count(“[abc]”时一起计算三个字母的出现次数
将计算字符串中出现的这三个字母的总数。因此,第一个字母将返回2表示“abcabc”,0表示“cbacba”,而第二个字母在这两种情况下都将返回6。将模式括在
[]
中是一个好主意+1为什么用括号括起来[{?要在f字符串中使用变量,请将它们用大括号括起来,例如
print(f“2+2等于{2+2}!”)
至于方括号
count(“abc”)
将在
count([abc]”)时一起计算三个字母的出现次数
将计算字符串中出现的这三个字母的总数。因此,第一个字母将返回2表示“abcabc”,0表示“cbacba”,而第二个字母在这两种情况下都将返回6。当您在每个字符串上循环时,速度要慢得多
len(字符串.标点符号)
次数当您在每个字符串上循环时,速度要慢得多
len(string.标点符号)
次数