【问题标题】:Vectorized alternative to iterrows : Semantic Analysisiterrows 的矢量化替代方案:语义分析
【发布时间】:2021-08-09 10:14:45
【问题描述】:

您好,我目前正在进行语义推文分析,并希望使用 Numpy Vectorization 提高我的代码运行时间。

我曾尝试增强我的代码一段时间,但没有成功。 我可以将循环迭代中的公式输入到函数中并通过 Numpy.vectorize 应用它吗?

ss = SentimentIntensityAnalyzer()

for index, row in tw_list["full_text"].iteritems():
    score = ss.polarity_scores(row)
    neg = score["neg"]
    neu = score["neu"]
    pos = score["pos"]
    comp = score["compound"]
    if neg > pos:
        tw_list.loc[index, "sentiment"] = "negative"
    elif pos > neg:
        tw_list.loc[index, "sentiment"] = "positive"
    else:
        tw_list.loc[index, "sentiment"] = "neutral"
        tw_list.loc[index, "neg"] = neg
        tw_list.loc[index, "neu"] = neu
        tw_list.loc[index, "pos"] = pos
        tw_list.loc[index, "compound"] = comp

【问题讨论】:

  • Afaik,矢量化不会提高代码速度,因为它是一种伪装的 for 循环。

标签: pandas algorithm dataframe numpy semantics


【解决方案1】:

您可以使用 apply 函数,而不是遍历数据框中的行。

def get_sentiments(text):
    score = ss.polarity_scores(text)
    neg = score["neg"]
    neu = score["neu"]
    pos = score["pos"]
    comp = score["compound"]
    if neg > pos:
        sentiment = "negative"
    elif pos > neg:
        sentiment = "positive"
    else:
        sentiment = "neutral"
    return sentiment,neg,neu,pos,comp
    
tw_list[["sentiment","neg","neu","pos","comp"]] = tw_list["full_text"].apply(get_sentiments,result_type='broadcast')

这应该会提高性能

【讨论】:

    猜你喜欢
    • 2016-09-28
    • 1970-01-01
    • 2022-12-22
    • 2018-12-11
    • 2020-08-02
    • 2021-12-11
    • 1970-01-01
    • 2020-08-29
    • 2019-12-21
    相关资源
    最近更新 更多