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

前端 未结 2 334
无人共我
无人共我 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
    
    0 讨论(0)
  • 2021-01-20 02:30

    Using str.contains

    df.Name.str.contains('John').sum()
    Out[246]: 3
    

    Or we using list and map with in

    sum(list(map(lambda x : 'John' in x,df.Name)))
    Out[248]: 3
    
    0 讨论(0)
提交回复
热议问题