【问题标题】:Pandas str.countPandas str.count
【发布时间】:2016-11-30 21:33:01
【问题描述】:

考虑以下数据框。我想计算出现在字符串中的“$”的数量。我在 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 中,字符串模块中的count 函数返回正确的结果。

>>> a = "$$$$abcd"
>>> a.count('$')
4
>>> a = '$abcd$dsf$'
>>> a.count('$')
3

【问题讨论】:

  • 我什至不知道str.count...谢谢!

标签: python pandas


【解决方案1】:

$ 在 RegEx 中有一个特殊的含义——它是行尾,所以试试这个:

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

【讨论】:

  • 如果 df["A"] 没有任何值会发生什么,仍然在计数
  • @pyd,你说“if df["A"] doesnt have any value”是什么意思?你的意思是空的DF?
【解决方案2】:

正如其他答案所指出的,这里的问题是$ 表示行尾。如果您不打算使用正则表达式,您可能会发现使用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

【讨论】:

  • 我认为为这么小的系列安排时间没有多大意义。也就是说,随着它变得更大,差异更加明显!编辑:真的 count 应该像其他 str 方法一样有一个 regex=False 标志。
  • 公平点。另一位评论者实际上在再次删除他们的评论之前提出了同样的建议,所以我尝试了一个由 10000 个随机整数组成的系列;在这种情况下,我看到的时间分别约为 8.4 毫秒和 6.1 毫秒。
  • 我认为None 有问题 - str.count 工作并申请否。
【解决方案3】:

尝试使用模式[$],这样它就不会将$ 视为字符结尾(请参阅此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

【讨论】:

    【解决方案4】:

    从@fuglede 得到启发

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

    正如@jezrael 所指出的,当存在空类型时,上述操作会失败,所以...

    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
    

    【讨论】:

    • 但是添加一个通知 - 在 df 中必须没有 NaN,然后会出错。我不确定,但apply 解决方案似乎有同样的问题
    • @jezrael 很有趣。会玩
    • 完全正确 - 测试它df = pd.DataFrame(['$$a', '$$b', None], columns=['A'])
    猜你喜欢
    • 2012-10-06
    • 2020-10-01
    • 2018-11-01
    • 2021-07-30
    • 2020-08-04
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    相关资源
    最近更新 更多