Garvey
Garvey

Reputation: 1309

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?

Upvotes: 3

Views: 83

Answers (4)

Axis
Axis

Reputation: 2132

you can try this;

for i in my_series:
    print (i.count('a'))

this gives each your series letter

Upvotes: 1

AChampion
AChampion

Reputation: 30268

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

Upvotes: 2

Jacob G.
Jacob G.

Reputation: 29700

To find out how many Strings in each List contain the letter a, you can use the following:

l = ['wdq', 'sda', 'qaaa']

print(sum([1 for x in l if 'a' in x]))

This prints the following:

2

Upvotes: 0

Bui Anh Tuan
Bui Anh Tuan

Reputation: 920

a = ['a', '12asf3', 'sdf']
b = ['gfdg5', '   ', 'vag gfd4']
c = [' fd4 ', 'sfsa fa', 'df4 a']

abc = [a, b, c]

for mem in abc:
  counter = 0
  for str in mem:
    if 'a' in str:
      counter += 1
  print abc.index(mem), mem, counter

Output:

0 ['a', '12asf3', 'sdf'] 2
1 ['gfdg5', '   ', 'vag gfd4'] 1
2 [' fd4 ', 'sfsa fa', 'df4 a'] 2

Upvotes: 0

Related Questions