简体   繁体   中英

Iterating over a DataFrame and appending the score into a column

When I run this code below, it returns 'float' object has no attribute 'encode' Im not sure what Im doing wrong, but I want to get the VADER sentiment values for the Titles (which is in a large dataframe) but Im not sure where im going wrong, or how to convert the type of variable to make the object iterable. And then appending the 'compound' scores into the dataframe. I have tried iteration code like:

pd.concat([bitcoin,bitcoin['Title'].apply(lambda r: pd.Series(analyzer.polarity_scores(r)))],axis=1) and score_compound = bitcoin['Title'].apply(lambda r: analyzer.polarity_scores(r)['compound'])

import nltk
import pandas as pd

analyzer = SentimentIntensityAnalyzer()
bitcoin = pd.read_csv("Subreddit_Bitcoin_2021.csv")

score_compound = []

for i in range(0, bitcoin.shape[0]):
               score = analyzer.polarity_scores(bitcoin.iloc[i][1])
               score1 = score['compound']
               score_compound.append(score1)```


Without your data to work on, it is har to know. I saw you posted the same question elsewhere and some data so I tested it on:

 index                                               text
0      0  I can’t believe Bitcoin is going to hit 100k b...
1      1  What new Bitcoin related project are you the m...
2      2  Yin decline is about to end! Historical data s...
3      3  If you discovered a way to model turning $100 ...
4      4  Happy New Year and some nice Gains !! 🎆🎆🎆🎇🎇🎇🎆🎆...

and with a completion of your code (please, for further notice, do share which libraries you import):

from nltk import *
import pandas as pd
import vader
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()

bitcoin = df

score_compound = []

for i in range(0, bitcoin.shape[0]):
               score = analyzer.polarity_scores(bitcoin.iloc[i][1])
               score1 = score['compound']
               score_compound.append(score1)
                
                
score_compound  

which returns:

[0.0258, 0.4005, 0.0, 0.6199, 0.9421]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM