简体   繁体   English

"如何将用户定义的函数应用于熊猫数据框中的列?"

[英]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.

相关问题 当我使用pandas DataFrame groupby然后应用用户定义的函数时,调用了多少个函数? - How many function calls when I use pandas DataFrame groupby and then apply user-defined function? 适用于整个数据帧的用户定义函数涉及pandas中的另一个数据帧 - apply to the entire dataframe a user-defined function involving another dataframe in pandas 当给定某个条件时,通过pandas数据帧的列中的用户定义函数输入值 - Input values through a user-defined function in a column of a pandas dataframe when a certain condition is given 如何使用 apply(基于用户定义的函数)向数据框添加新行和多行? - How to add new and multiple rows to a dataframe using apply (based on a user-defined function)? 使用用户定义函数中的值创建一个新的pandas列 - Create a new pandas column with a value from a user-defined function 如何在 pandas 中的分组数据上按列应用用户定义的 function - how to apply a user defined function column wise on grouped data in pandas 如何在pandas中使用用户自定义的function根据列值和Timestamp返回一个值 - How to return a value based on column value and Timestamp using user-defined function in pandas 使用用户定义的函数声明一个熊猫系列 - Declaring a pandas series with a user-defined function 用户自定义 function 为 pandas groupby - user-defined function for pandas groupby 向量化熊猫数据框将函数应用于python中的用户定义函数 - Vectorising pandas dataframe apply function for user defined function in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM