12

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?

Troy Poulter
  • 677
  • 1
  • 8
  • 29
user2585048
  • 123
  • 1
  • 1
  • 5

1 Answers1

26

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)
JAV
  • 675
  • 6
  • 10