Apply textblob in for each row of a dataframe

user2585048 picture user2585048 · Apr 19, 2017 · Viewed 10.9k times · Source

i have a data frame with a col which has text. I want to apply textblob and calculate sentiment value for each row.

text                sentiment

this is great
great movie great story

When i execute the below code:

df['sentiment'] = list(map(lambda tweet: TextBlob(tweet), df['text']))

I get the error:

TypeError: The `text` argument passed to `__init__(text)` must be a string, not <class 'float'>

How do you apply textBLob to each row of a col in a dataframe to get the sentiment value?

Answer

JAV picture JAV · Apr 19, 2017

You can use .apply:

df['sentiment'] = df['text'].apply(lambda tweet: TextBlob(tweet).sentiment)

Sentiment returns a namedtuple of the form Sentiment(polarity, subjectivity).

But are you sure each row of df['text'] is in string format? If not, you could try below to return None if the text cannot be processed by TextBlob:

def sentiment_calc(text):
    try:
        return TextBlob(text).sentiment
    except:
        return None

df['sentiment'] = df['text'].apply(sentiment_calc)