[英]How to apply a user-defined function to a column in pandas dataframe?
I'm working on an NLP task.我正在处理 NLP 任务。 I defined a function to conduct aspect extraction and sentiment based on the aspect and dependency parsing.
我定义了一个基于方面和依赖解析进行方面提取和情感的函数。 The function looks like:
该函数如下所示:
import spacy
nlp = spacy.load('en_core_web_sm')
def aspect_sentiment(text):
aspects = []
for sentence in text:
doc = nlp(sentence)
descriptive_term = ''
target = ''
for token in doc:
if token.dep_ == 'nsubj' and token.pos_ == 'NOUN':
target = token.text
if token.pos_ == 'ADJ':
prepend = ''
for child in token.children:
if child.pos_ != 'ADV':
continue
prepend += child.text + ' '
descriptive_term = prepend + token.text
aspects.append({'aspect': target, 'description': descriptive_term})
for aspect in aspects:
aspect['polarity'] = TextBlob(aspect['description']).sentiment.polarity
aspect['subjectivity'] = TextBlob(aspect['description']).sentiment.subjectivity
return(aspects)
You can use df[col].apply(fn)<\/code> instead, which will run the function once on each element in a pandas Series.
您可以改用
df[col].apply(fn)<\/code> ,它将在熊猫系列中的每个元素上运行一次该函数。
Just need to adjust
aspect_sentiment<\/code> a bit to expect individual sentences instead of a list of sentences.
只需要稍微调整
aspect_sentiment<\/code>以期望单个句子而不是句子列表。
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.