考虑以下数据框。我想计算字符串中出现的“$”的数量。我在 pandas ( http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.count.html) 中使用 str.count
函数。
>>> import pandas as pd
>>> df = pd.DataFrame(['$$a', '$$b', '$c'], columns=['A'])
>>> df['A'].str.count('$')
0 1
1 1
2 1
Name: A, dtype: int64
我原以为结果是 [2,2,1]
。我究竟做错了什么?
在 Python 中,string 模块中的 count
函数返回正确的结果。
>>> a = "$$$$abcd"
>>> a.count('$')
4
>>> a = '$abcd$dsf$'
>>> a.count('$')
3
最佳答案
$
在 RegEx 中有特殊含义 - 它是行尾,所以试试这个:
In [21]: df.A.str.count(r'\$')
Out[21]:
0 2
1 2
2 1
Name: A, dtype: int64
关于python - Pandas 海峡计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40875649/