熊猫str.count

时间:2016-11-29 20:58:38

标签: python pandas

考虑以下数据帧。我想计算一个字符串中出现的'$'的数量。我在pandas(http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.count.html)中使用public function boot() { DB::listen(function ($query) { dd($query); }); } 函数。

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 。我究竟做错了什么?

在Python中,字符串模块中的[2,2,1]函数返回正确的结果。

count

4 个答案:

答案 0 :(得分:5)

$在RegEx中有特殊含义 - 它的行尾,请试试这个:

In [21]: df.A.str.count(r'\$')
Out[21]:
0    2
1    2
2    1
Name: A, dtype: int64

答案 1 :(得分:3)

正如其他答案所指出的,这里的问题是$表示该行的结束。如果您不打算使用正则表达式,您可能会发现使用str.count(即内置类型str中的方法)比它的pandas对应更快;

In [39]: df['A'].apply(lambda x: x.count('$'))
Out[39]: 
0    2
1    2
2    1
Name: A, dtype: int64

In [40]: %timeit df['A'].str.count(r'\$')
1000 loops, best of 3: 243 µs per loop

In [41]: %timeit df['A'].apply(lambda x: x.count('$'))
1000 loops, best of 3: 202 µs per loop

答案 2 :(得分:2)

尝试使用模式[$],这样就不会将$视为字符的结尾(请参阅此cheatsheet),如果将其放在方括号[]中,则会将其视为作为字面字符:

In [3]:
df = pd.DataFrame(['$$a', '$$b', '$c'], columns=['A'])
df['A'].str.count('[$]')

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

答案 3 :(得分:1)

从@fuglede获取提示

pd.Series([x.count('$') for x in df.A.values.tolist()], df.index)
如@jezrael所指出的那样,当存在null类型时上述失败,所以......

def tc(x):
    try:
        return x.count('$')
    except:
        return 0

pd.Series([tc(x) for x in df.A.values.tolist()], df.index)

时间

np.random.seed([3,1415])
df = pd.Series(np.random.randint(0, 100, 100000)) \
       .apply(lambda x: '\$' * x).to_frame('A')

df.A.replace('', np.nan, inplace=True)

def tc(x):
    try:
        return x.count('$')
    except:
        return 0

enter image description here