python - 如何针对数据框优化此方法?
问题描述
我会优化这个方法:
def get_sentiment_score(text):
text = text.split()
positive = 0
negative = 0
for word in text:
if word in positive_words:
positive += 1
elif word in negative_words:
negative += 1
score = positive - negative
if score == 0:
return "UNCERTAIN"
return "POSITIVE" if score > 0 else "NEGATIVE"
df["sentiment_polarity"] = df["text"].apply(lambda row: get_sentiment_score(str(row)))
变量positive_words 和negative_words 在列表中每个都包含超过2000 个元素,并且数据框有270K+ 行。
我目前花费的总时间是 1000 多秒。
我想把它降低到 100 秒以下。
提前致谢。
解决方案
我会使用和set
拆分。numpy
pandas
import numpy as np
import pandas as pd
dataf = pd.DataFrame({"text":["hello world is over", "go big or go home"]})
# transform your lists to set
positive_set = {"world", "over"}
negative_set = {"is", "go"}
# use intersection and find length
def check(s:set) -> int:
positive = len(s.intersection(positive_set))
negative = len(s.intersection(negative_set))
return positive - negative
# apply it using pandas string slips
dataf["sentiment"] = dataf["text"].str.split().map(set).map(check)
# use numpy to tag
condition = [dataf["sentiment"].gt(0), dataf["sentiment"].lt(0), dataf["sentiment"].eq(0)]
choices = ["POSITIVE", "NEGATIVE", "UNCERTAIN"]
dataf["sentiment"] = np.select(condition, choices)
推荐阅读
- c# - EF Core ICollection 不包含“包含”的定义
- java - Camel 从 FTP 读取文件并存储在本地资源文件夹中
- solr - Solr/Lucene 上下文同义词过滤器
- sql-server - 在 SQL Server / Liquibase 中,INSERT 查询是否会自动创建一个没有 CREATE 架构的表(如果它不存在)?
- mysql - ServiceStack.OrmLite:StringLengthAttribute.MaxText 产生“LONGTEXT”-如何设置为“TEXT”?
- java - Spring boot - 没有嵌入式 tomcat 的 Rest Call 客户端
- gettext - 是否有命令来标记和清除 po 文件中具有相同翻译的不同消息?
- amazon-web-services - ECS 无效参考格式错误
- firebase - Firebase web auth via Google SSO - 如何知道用户是否注册或登录
- wordpress - 模组重写 - .htaccess