How to get the number of times a piece if word is inside a particular column in pandas?

前端 未结 2 357
无人共我
无人共我 2021-01-20 01:43

I\'ll try to use a simple example to describe my problem.

I have a csv file with many columns. One of this columns\' header is \"names\".

In this column \"n

2条回答
  •  感动是毒
    2021-01-20 02:08

    You can use pandas.Series.str.count to count the number of times in each row a pattern is encountered.

    df.names.str.count('John').sum()
    
    3
    

    In this example, it matches OP's output. However, this would produce different results if John appeared more than once in one row. Suppose we had this df instead:

    df
    
                     names
    0            John John
    1        John M John M
    2  Mike John Mike John
    3        Audrey Audrey
    4        Andrew Andrew
    

    Then my answer produces

    df.names.str.count('John').sum()
    
    6
    

    While Wen's answer produces

    df.names.str.contains('John').sum()
    
    3
    

提交回复
热议问题