NeS*_*ack 4 python contains special-characters pandas
我正在尝试df['column_name'].str.count("+")在 python 熊猫中使用,但我收到
“错误:没有什么可重复的”
. 使用常规字符,该方法有效,例如df['column_name'].str.count("a")工作正常。
另外,“^”符号也有问题。如果我使用df['column_name'].str.contains("^")结果不正确 - 看起来“^”被解释为“”(空白)。
令人惊讶的是,如果我在常规的非熊猫字符串上使用.count("+")和.contains("^"),它们工作得非常好。
简单的工作示例:
df = pd.DataFrame({'column1': ['Nighthawks+', 'Dragoons'], 'column2': ['1st', '2nd']}, columns = ['column1', 'column2'])
Run Code Online (Sandbox Code Playgroud)
当应用df["column1"].str.contains("^")一个得到“真,真”但应该是“假,假”。
当应用df["column1"].str.count("+")一个得到
“错误:没有什么可重复的”
但是,在熊猫之外,"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
Run Code Online (Sandbox Code Playgroud)
此外,当您这样做时,df['a'].str.count('^')只会1为所有行返回:
In[12]:
df['a'].str.count('^')
Out[12]:
0 1
1 1
2 1
3 1
Name: a, dtype: int64
Run Code Online (Sandbox Code Playgroud)
同样,您需要转义该模式:
In[16]:
df['a'].str.count('\^')
Out[16]:
0 1
1 1
2 0
3 0
Name: a, dtype: int64
Run Code Online (Sandbox Code Playgroud)
编辑
关于count普通字符串和 a之间的语义差异Series,count在 python 上str只进行字符计数,但str.count采用正则表达式模式。的^和+都是需要,如果你正在寻找这些字符用反斜杠转义特殊字符
对于str.count()特殊字符,您需要使用反斜杠来表示正则表达式模式。(上面@EdChum 对此进行了详细解释)。
另一方面,str.contains()我们不需要对正则表达式模式使用反斜杠。只需添加regex=False类似参数df['a'].str.contains("+", regex=False))即可搜索并查找包含特殊字符的字符串。
| 归档时间: |
|
| 查看次数: |
6772 次 |
| 最近记录: |