Python Pandas无法识别特殊字符 [英] Python pandas doesn't recognize special characters

查看:633
本文介绍了Python Pandas无法识别特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试在python大熊猫中使用 df ['column_name']。str.count( +),但我收到

I am trying to use df['column_name'].str.count("+") in python pandas, but I receive


错误:没什么可重复的

"error: nothing to repeat"

。使用常规字符时,该方法有效,例如 df ['column_name']。str.count( a)可以正常工作。

. With the regular characters the method works, e.g. df['column_name'].str.count("a") works fine.

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

Also, there is a problem with the "^"-sign. If I use df['column_name'].str.contains("^") the result is incorrect - it looks like "^" gets interpreted as " " (empty space).

令人惊讶的是,如果我使用 .count( +)。在常规的非大熊猫字符串上包含( ^)即可正常工作。

Surprisingly, if I use .count("+") and .contains("^") on a regular, non-pandas string they work perfectly fine.

简单的工作示例:

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

在申请 df [ column1]。str.contains( ^)会得到 True,True,但应为 False,False。

When applying df["column1"].str.contains("^") one gets "True, True" but is should be "False, False".

并在应用 df [ column1]。str.count( +)时得到


错误:没什么可重复的

"error: nothing to repeat"

但是在熊猫外面, bla ++。count( +)正确给出结果 2。

But then, outside of panda, "bla++".count("+") gives correctly the result "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('^')时,这只会返回 1 所有行:

Also when you do df['a'].str.count('^') this just returns 1 for all rows:

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

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

同样,您需要转义模式:

Again you need to escape the pattern:

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

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

编辑

关于普通字符串上的 count 和在系列上, <$ c python str 上的$ c> count 只进行字符计数,但是 str.count 采用正则表达式模式。 ^ + 是特殊字符,如果要搜索这些字符,则必须使用反斜杠转义

Regarding the semantic difference between count on a normal string and on a Series, count on a python str just does a character count, but str.count takes a regex pattern. The ^ and + are special characters which need to be escaped with a backslash if you are searching for those characters

这篇关于Python Pandas无法识别特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆