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

如何在Pandas中实现字符串数据与数值的相关性分析及关联单词筛选?

如何在Pandas中计算文本单词与数值的相关性

嘿,你的需求非常明确!Pandas本身并没有直接支持文本(单词)与数值列相关性计算的原生功能,但我们可以结合特征工程把文本转换成可计算的数值特征,再用Pandas的相关性分析工具来实现。下面我用一个具体的示例一步步教你怎么做:

步骤1:准备示例数据

先构造一个和你描述类似的DataFrame,模拟句子和对应的score:

import pandas as pd

data = {
    "sentence": [
        "hello world hello",
        "goodbye foo",
        "hello bar hello",
        "test hello",
        "goodbye test"
    ],
    "score": [8, 3, 7, 6, 2]
}
df = pd.DataFrame(data)

步骤2:把文本转换成数值特征

我们用sklearn.feature_extraction.text.CountVectorizer把句子拆成单词,生成一个“词袋”矩阵——每一行对应原DataFrame的一个句子,每一列对应一个单词,值是该单词在句子中的出现次数。

from sklearn.feature_extraction.text import CountVectorizer

# 初始化向量器,可选去掉停用词(比如"the"这种无意义词)
vectorizer = CountVectorizer(stop_words="english")
# 拟合并转换文本数据
word_counts = vectorizer.fit_transform(df["sentence"])
# 转换成DataFrame,列名是单词
word_df = pd.DataFrame(word_counts.toarray(), columns=vectorizer.get_feature_names_out())

步骤3:合并特征与原数值列

把单词计数的DataFrame和原score列合并,方便后续计算相关性:

combined_df = pd.concat([word_df, df["score"]], axis=1)

步骤4:计算单词与score的相关性

用Pandas的corr()方法计算每个单词列与score列的皮尔逊相关系数(默认就是这个,也可以指定其他方法比如spearman):

correlations = combined_df.corr()["score"].drop("score")  # 去掉score自己和自己的相关性

步骤5:找出相关性最高和最低的单词

对相关系数排序就能得到你要的结果:

# 相关性最高的单词
top_word = correlations.sort_values(ascending=False).head(1)
# 相关性最低的单词
bottom_word = correlations.sort_values(ascending=False).tail(1)

print("与score相关性最高的单词:")
print(top_word)
print("\n与score相关性最低的单词:")
print(bottom_word)

运行这段代码,你会看到"hello"和score的相关性最高,而"goodbye"相关性最低,完全符合你的预期!

可选优化:用TF-IDF代替词袋计数

如果你觉得单纯的单词计数不够准确(比如高频但无意义的词权重太高),可以用TfidfVectorizer代替CountVectorizer,它会根据单词的重要性调整权重,计算出来的相关性可能更合理:

from sklearn.feature_extraction.text import TfidfVectorizer

tfidf_vectorizer = TfidfVectorizer(stop_words="english")
tfidf_matrix = tfidf_vectorizer.fit_transform(df["sentence"])
tfidf_df = pd.DataFrame(tfidf_matrix.toarray(), columns=tfidf_vectorizer.get_feature_names_out())
combined_tfidf_df = pd.concat([tfidf_df, df["score"]], axis=1)
tfidf_correlations = combined_tfidf_df.corr()["score"].drop("score")

这样就完成啦!整个流程的核心就是把文本转换成数值特征,再用Pandas的原生相关性计算功能处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:09:20