【问题标题】:Count appearances of a string throughout columns in pandas计算熊猫列中字符串的出现次数
【发布时间】:2018-04-04 06:05:16
【问题描述】:

考虑以下数据框:

import pandas as pd
df = pd.DataFrame(["What is the answer", 
                   "the answer isn't here, but the answer is 42" , 
                   "dogs are nice", 
                   "How are you"], columns=['words'])
df
                                         words
0                           What is the answer
1  the answer isn't here, but the answer is 42
2                                dogs are nice
3                                  How are you

我想统计某个字符串出现的次数,它可能在每个索引中重复几次。

比如我想统计the answer出现的次数。 我试过了:

df.words.str.contains(r'the answer').count()

我希望有一个解决方案,但输出是4。 我不明白为什么。 the answer 出现 3 次。

What is **the answer**
**the answer** isn't here, but **the answer** is 42

注意:搜索字符串可能在一行中出现多次

【问题讨论】:

    标签: python regex pandas dataframe contains


    【解决方案1】:

    你需要str.count

    In [5285]: df.words.str.count("the answer").sum()
    Out[5285]: 3
    
    In [5286]: df.words.str.count("the answer")
    Out[5286]:
    0    1
    1    2
    2    0
    3    0
    Name: words, dtype: int64
    

    【讨论】:

    • 哇,这么快:-)
    猜你喜欢
    • 2019-07-09
    • 2018-03-12
    • 2018-07-17
    • 2020-12-24
    • 2022-01-06
    • 2019-02-22
    • 1970-01-01
    • 2023-03-04
    • 2020-12-10
    相关资源
    最近更新 更多