python - Pandas 海峡计数

标签 python pandas

考虑以下数据框。我想计算字符串中出现的“$”的数量。我在 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/

相关文章:

python - Pandas 按某些列分组

pandas - KeyError : "None of [Index([. ..] 在 [列] 中

python - 如何在Python中使用concat将数据帧的每一行转换为新列

python - 在垃圾收集后保留循环引用

python - 将文档字符串放在 Python 属性上的正确方法是什么?

python mysqldb 打印文本,即使代码中没有打印语句

python - 创建使用百分比而不是计数的 matplotlib 或 seaborn 直方图?

python - 如何在每行末尾添加一个\n

python - 忽略大小写的字符串排序列表

python - Pandas DataFrame 滚动计数