Garvey Garvey - 2 months ago 15
Python Question

How to count string with pattern in series object?

Suppose a data like this:

>>> data
x
0 [wdq, sda, q]
1 [q, d, qasd]
2 [d, b, sdaaaa]


I wonder how many string contains
a
in each list, which means I need an answer like this:

>>> data
x count_a
0 [wdq, sda, q] 1
1 [q, d, qasd] 1
2 [d, b, sdaaaa] 1


How can I do this in python?

Answer Source

Assuming this is a pandas.DataFrame and x is a list object:

df['count_a'] = df['x'].apply(lambda x: sum('a' in e for e in x))