Garvey Garvey - 10 months ago 50
Python Question

How to count string with pattern in series object?

Suppose a data like this:

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

I wonder how many string contains
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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download