Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply textblob in for each row of a dataframe

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?

like image 908
user2585048 Avatar asked Apr 19 '17 02:04

user2585048


Video Answer


1 Answers

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)
like image 193
JAV Avatar answered Oct 08 '22 10:10

JAV