Python pandas 不识别特殊字符

Python pandas doesn't recognize special characters

我正在尝试在 python pandas 中使用 df['column_name'].str.count("+"),但我收到了

"error: nothing to repeat"

。对于常规字符,该方法有效,例如df['column_name'].str.count("a") 工作正常。

此外,“^”符号也有问题。如果我使用 df['column_name'].str.contains("^") 结果不正确 - 看起来“^”被解释为“”(空 space)。

令人惊讶的是,如果我在常规的非 pandas 字符串上使用 .count("+").contains("^"),它们工作得很好。

简单的工作示例:

df = pd.DataFrame({'column1': ['Nighthawks+', 'Dragoons'], 'column2': ['1st', '2nd']}, columns = ['column1', 'column2'])

应用 df["column1"].str.contains("^") 时得到 "True, True" 但应该是 "False, False".

当应用 df["column1"].str.count("+") 时,一个人会得到

"error: nothing to repeat"

但是,在 panda 之外,"bla++".count("+") 给出了正确的结果“2”。

有什么解决办法吗?谢谢

您需要转义加号:

In[10]:
df = pd.DataFrame({'a':['dsa^', '^++', '+++','asdasads']})
df

Out[10]: 
          a
0      dsa^
1       ^++
2       +++
3  asdasads

In[11]:
df['a'].str.count("\+")

Out[11]: 
0    0
1    2
2    3
3    0
Name: a, dtype: int64

此外,当您对所有行执行 df['a'].str.count('^') 这只是 returns 1 时:

In[12]:
df['a'].str.count('^')

Out[12]: 
0    1
1    1
2    1
3    1
Name: a, dtype: int64

再次需要转义模式:

In[16]:
df['a'].str.count('\^')

Out[16]: 
0    1
1    1
2    0
3    0
Name: a, dtype: int64

编辑

关于普通字符串 countSeries 之间的语义差异,count on a python str just does a character count, but str.count 采用正则表达式模式。 ^+ 是特殊字符,如果您要搜索这些字符

,则需要使用反斜杠对其进行转义

in str.count() 对于特殊字符,您需要使用 反斜杠 作为正则表达式模式。 (上面的@EdChum有详细解释)。

另一方面,在 str.contains() 中,我们不需要对正则表达式模式使用反斜杠。只需要加上regex=False参数,比如df['a'].str.contains("+", regex=False)),就可以搜索到包含特殊字符的字符串。