Reputation: 26676
Data Frame
df=pd.DataFrame({'StringMatch':['[mother]','[priest, mother,mother father]','[father, mother]']})
df
desired output
df=pd.DataFrame({'StringMatch':['[mother]','[priest, mother,mother father]','[father, mother]'], 'StringMatchCount':['{mother:1}', '{priest:1, mother:2, father:1}','{father:1, mother:1}']})
I tried the following:
df['StringMatchCount'] =df['StringMatch'].str.count(k)
df
Upvotes: 1
Views: 23
Reputation: 862751
Use:
from collections import Counter
#convert str repr of lists to lists if necessary
df['StringMatch'] = df['StringMatch'].str.strip('[]').str.split(',\s*|\s+')
#add Counter
df['StringMatchCount'] = df['StringMatch'].apply(Counter)
print (df)
StringMatch StringMatchCount
0 [mother] {'mother': 1}
1 [priest, mother, mother, father] {'priest': 1, 'mother': 2, 'father': 1}
2 [father, mother] {'father': 1, 'mother': 1}
Upvotes: 1