Apply textblob in for each row of a dataframe

我的梦境 提交于 2019-12-30 05:08:08

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/43485469/apply-textblob-in-for-each-row-of-a-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!