panda
panda

Reputation: 625

How to print occurence of given string on pandas data frame column?

I have the following dataframe.

import pandas as pd

data = [['Alexa',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'])
df

to check whether certain characters are present in Name column.

mylist=['a','e']
pattern = '|'.join(mylist)
df['contains']=df['Name'].str.contains(pattern)

Above code will give true or false if mylist values are present.

How to get letters column in the output.

    Name    Age contains  letters
0   Alexa   10  True      e a 
1   Bob     12  False     
2   Clarke  13  True      a e

Upvotes: 1

Views: 34

Answers (1)

user3483203
user3483203

Reputation: 51165

You can use set intersection here, and a list comprehension, which will be faster than the pandas string methods:

check = set('ae')
df.assign(letters=[set(n.lower()) & check for n in df.Name])

     Name  Age letters
0   Alexa   10  {a, e}
1     Bob   12      {}
2  Clarke   13  {a, e}

The alternative would be something like:

df.assign(letters=df.Name.str.findall(r'(?i)(a|e)'))

     Name  Age    letters
0   Alexa   10  [A, e, a]
1     Bob   12         []
2  Clarke   13     [a, e]

The second approach A) will include duplicates, and B), will be slower:

In [89]: df = pd.concat([df]*1000)

In [90]: %timeit df.Name.str.findall(r'(?i)(a|e)')
2.34 ms ± 93.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [91]: %timeit [set(n.lower()) & check for n in df.Name]
1.45 ms ± 23.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Upvotes: 3

Related Questions