【问题标题】:Counting specific keywords in a dataframe计算数据框中的特定关键字
【发布时间】:2019-12-25 13:26:19
【问题描述】:

我有一个这样的数据框:

    A
0   Please wait outside of the house
1   A glittering gem is not enough.
2   The memory we used to share is no longer coher...
3   She only paints with bold colors; she does not...

我有一组关键字:

keywords = ["of","is","she"]

如何为每个关键字创建一个列,其中包含该关键字在我的数据框的每个句子中出现的次数?它看起来像:

                                                   A  of  is  she
0                   Please wait outside of the house   1   0    0
1                    A glittering gem is not enough.   0   1    0
2  The memory we used to share is no longer coher...   0   1    0
3  She only paints with bold colors; she does not...   0   0    2

注意:我查看了how to count specific words from a pandas Series?,但它没有回答我的问题。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我假设您正在寻找不区分大小写的匹配项。

    import pandas as pd
    df = pd.DataFrame({
        'A': [
            'Please wait outside of the house',
            'A glittering gem is not enough.',
            'The memory we used to share is no longer coher...',
            'She only paints with bold colors; she does not...'
        ]
    })
    keywords = ["of","is","she"]
    for keyword in keywords:
        df[keyword] = df['A'].apply(lambda _str: _str.lower().count(keyword))
    print(df)
    

    输出

                                                       A  of  is  she
    0                   Please wait outside of the house   1   0    0
    1                    A glittering gem is not enough.   0   1    0
    2  The memory we used to share is no longer coher...   0   1    0
    3  She only paints with bold colors; she does not...   0   0    2
    

    【讨论】:

      【解决方案2】:

      你也可以这样做:

      df['is'] = df.A.str.count(r'is', flags=re.IGNORECASE)
      df['of'] = df.A.str.count(r'of', flags=re.IGNORECASE)
      df['she'] = df.A.str.count(r'she', flags=re.IGNORECASE)
      
      
                                                         A  of  is  she
      0                   Please wait outside of the house   1   0    0
      1                    A glittering gem is not enough.   0   1    0
      2  The memory we used to share is no longer coher...   0   1    0
      3  She only paints with bold colors; she does not...   0   0    2
      

      【讨论】:

        猜你喜欢
        • 2019-09-18
        • 1970-01-01
        • 2017-12-03
        • 2021-03-22
        • 2023-01-18
        • 2018-03-13
        • 1970-01-01
        • 1970-01-01
        • 2016-11-06
        相关资源
        最近更新 更多