How might I count the occurrence of a specific character that is different in every row

Viewed 39

I would like to count how often a specific character (that is different in every row) appears in a dataframe series. Example dataframe:

givenletter phrase
w whatwhatwhat
q queenbee
d devildonkey
n woohoo
e arrogant

Desired result:

givenletter phrase frequency
w whatwhatwhat 3
q queenbee 1
d devildonkey 2
n woohoo 0
e arrogant 0

Attempted code below just came back as 0 for all frequencies

df["frequency"] = df["phrase"].str.count(str(df["givenletter"]))

I've tried digging through similar stackoverflow questions but they all seem to deal with counting the occurrence of a character that doesn't change. Would be grateful for any advice on how I might correct my code.

2 Answers

Try

df['frequency'] = df.apply(lambda x:x['phrase'].count(x['givenletter']), axis=1)

A list comprehension is sufficient for this:

df["frequency"] = [phrase.count(letter) 
                   for phrase, letter 
                   in zip(df.phrase, df.givenletter)]
df    

    givenletter   phrase    frequency
0       w       whatwhatwhat    3
1       q       queenbee        1
2       d       devildonkey     2
3       n       woohoo          0
4       e       arrogant        0
Related