[英]Applying a function on pandas dataframe to perform a sentiment analysis
我有下面的 function 执行短语中的情绪分析并返回一个元组(sentiment, % NB classifier)
,例如(sadness, 0.78)
我想在 pandas dataframe df.Message 上应用这个df.Message
来分析它,然后再创建 2 个df.Prob
列df.Sentiment
,
代码如下:
def avalia(teste):
testeStemming = []
stemmer = nltk.stem.RSLPStemmer()
for (palavras_treinamento) in teste.split():
comStem = [p for p in palavras_treinamento.split()]
testeStemming.append(str(stemmer.stem(comStem[0])))
novo = extrator_palavras(testeStemming)
distribuicao = classificador.prob_classify(novo)
classe_array = [(classe, (distribuicao.prob(classe))) for classe in distribuicao.samples()]
inverse = [(value, key) for key, value in classe_array]
max_key = max(inverse)[1]
for each in classe_array:
if each[0] == max_key:
a=each[0] # returns the sentiment
b=each[1] # returns the probability
#print(each)
return a, b
单个字符串的示例:
avalia('i am sad today!')
(sadness, 0.98)
现在我有一个 dataframe 有 13k 行和一列:消息。 我可以将我的 function 应用到 dataframe 列并获得 pandas.series ,例如:
0 (surpresa, 0.27992165905522154)
1 (medo, 0.5632686358414051)
2 (surpresa, 0.2799216590552195)
3 (alegria, 0.5429940754962914)
我想使用这些信息在同一个 dataframe 中创建 2 个新列,如下所示。
Message Sentiment Probability
0 I am sad surpresa 0.2799
1 I am happy medo 0.56
我无法完成最后一部分。 请问有什么帮助吗?
尝试在 function 的末尾返回两个值,并使用apply()
将它们保存到单独的列中:
def avalia(teste):
testeStemming = []
stemmer = nltk.stem.RSLPStemmer()
for (palavras_treinamento) in teste.split():
comStem = [p for p in palavras_treinamento.split()]
testeStemming.append(str(stemmer.stem(comStem[0])))
novo = extrator_palavras(testeStemming)
distribuicao = classificador.prob_classify(novo)
classe_array = [(classe, (distribuicao.prob(classe))) for classe in distribuicao.samples()]
inverse = [(value, key) for key, value in classe_array]
max_key = max(inverse)[1]
for each in classe_array:
if each[0] == max_key:
a=each[0] # returns the sentiment
b=each[1] # returns the probability
return a, b
df.Sentiment, df.Prob = df.Message.apply(avalia)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.