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
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
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