2
from textblob import TextBlob

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

test_df['sentiment score'] = test_df['text'].apply(sentiment_calc)
test_df

I recently ran a code on my dataset to implement sentiment analysis using the TextBlob package. After running that, my sentiment column has the following output below (I did an example table with dummy numbers below).

 text   | sentiment score
 ------------------------
 nice   | (0.45, 4.33)
 good   | (0.45, 4.33)
 ok     | (0.45, 4.33)

And the output I would like to get is this, where I split the sentiment column into two columns, but add those columns onto the current dataframe.

text | polarity | subjectivity
------------------------------
nice |0.45      | 0.433
good |0.45      | 0.433
ok   |0.45      | 0.433

Is there a way to do this in Python 2.7?

3
  • Please edit your question to show the code that produced your example table. Commented Nov 4, 2017 at 18:14
  • Whoops. Edited with code to get the sentiment column. Commented Nov 4, 2017 at 19:13
  • So I am guessing test_df is a pd.DataFrame ? Commented Nov 4, 2017 at 20:41

1 Answer 1

2

This is what you want to do with pandas:

sentiment_series = df['sentiment score'].tolist()

columns = ['polarity', 'subjectivity']

df = pd.DataFrame(sentiment_series, columns=columns, index=df.index)
Sign up to request clarification or add additional context in comments.

1 Comment

This erases the other content on the 'df' data frame since it is replacing values in the data frame. is there any way to concat the new columns to the 'df'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.