You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python pandas计算数据框中分词语句的对应总得分

实现pandas分词句子得分计算的方案

首先将词元得分数据框转为字典,提升查询效率,假设存储词元得分的数据框名为score_df:

lemma_score_map = dict(zip(score_df['lemma'], score_df['v']))

之后直接对分词列做自定义映射求和即可,有两种常用写法:

写法1:自定义函数(可读性更高)

def count_total_score(word_list):
    total = 0.0
    for word in word_list:
        # 匹配到词元就加对应得分,未匹配到则加0
        total += lemma_score_map.get(word, 0.0)
    return total

df2['total_score'] = df2['lemmatized_nlp'].apply(count_total_score)

写法2:lambda简写(代码更简洁)

df2['total_score'] = df2['lemmatized_nlp'].apply(lambda x: sum(lemma_score_map.get(w, 0.0) for w in x))

大数据量优化方案

如果数据量超过十万行,建议用explode+merge+分组求和的方式,性能比apply更高:

# 保留原索引用于后续分组还原
df2 = df2.reset_index(names='original_idx')
# 拆分分词列表为单行单个词
exploded_df = df2.explode('lemmatized_nlp').rename(columns={'lemmatized_nlp': 'lemma'})
# 关联得分表
merged_df = exploded_df.merge(score_df, on='lemma', how='left')
# 按原索引分组求和,回填到原表
df2['total_score'] = merged_df.groupby('original_idx')['v'].sum().values

注意事项

  • 如果存在词元大小写不统一的情况,建议提前把score_df['lemma']和df2['lemmatized_nlp']里的所有词统一转成小写/大写,避免匹配遗漏
  • 不需要的无效词可以提前过滤,减少不必要的计算量

内容的提问来源于stack exchange,提问作者bonzo1971

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 05:54:08