Column term stores a set with a few strings (out of a fixed set of ~1000 strings).
df = pd.DataFrame([[{'city', 'mouse'}],
[{'mouse'}],
[{'blue'}]],
columns=['terms'])
Out[1]
terms
0 {mouse, city}
1 {mouse}
2 {blue}
I want to iterate over the rows and count occurrences of each unique term per row, so I plan to create a boolean column for each term found. Something like:
terms has_mouse has_city has_blue
0 {mouse, city} 1 1 0
1 {mouse} 1 0 0
2 {blue} 0 0 1
I tried this:
def count_terms_in_row(row):
for term in row['terms']:
row['has_{}'.format(term)] = 1
df.apply(count_terms_in_row, axis=1)
However, that didn't work as planned . What's the right approach here?
df.terms.apply(len)?