Skip to content
Advertisement

Running a for loop or .apply with a pandas series

I’m trying to run a for loop or .apply using lambdas for my pandas series. Here’s the code:

df['sentiment_score'] = df.apply(lambda x: analyzer.polarity_scores(x['Filtered_text']), axis=1)

What I’m trying to achieve is for each word in df['Filtered_text'], apply the analyzer.polartiy_scores(x['Filtered_text']) through the column.

An example of what is stored in df['Filtered_text']:

[website, needs, convinient, terrible]
[filters, mobile, version, site]

So for every one of those words, I’d like it to be applied to the analyzer.polarity_scores

I’ve also tried this:

df['sentiment_score'] = df['Filtered_text'].apply(lambda x: analyzer.polarity_scores(x))

But I get this error:

AttributeError: 'list' object has no attribute 'encode'

and this:

df['sentiment_score'] = df['Filtered_text'].apply(lambda x: [ft for ft in x: analyzer.polarity_scores(x)])

Thanks

Advertisement

Answer

I would use a list comprehension to solve this:

df['sentiment_score'] = df['Filtered_text'].apply(lambda x: [analyzer.polarity_scores(e) for e in x])
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement