
在数据分析和自然语言处理中,我们经常需要根据文本内容对其进行分类或打标签。一个常见的场景是,给定一组预定义的关键词类别(如“水果”、“动物”、“国家”),我们需要分析文本数据中哪些类别出现的频率最高,并以此来标记该文本。例如,如果一段话中“苹果”、“香蕉”出现的次数远多于“狗”、“猫”,那么这段话很可能属于“水果”类别。
本教程旨在解决以下问题:如何为Pandas DataFrame中的文本列,基于关键词的出现概率,自动生成一个代表最高概率类别的标签列。概率的计算方式为:某个类别中关键词的总出现次数除以该行文本的总词数。
要实现上述目标,我们需要掌握以下几个核心概念和技术:
我们将通过一个具体的Pandas DataFrame示例来演示整个实现过程。
首先,导入必要的Python库,并创建一个示例DataFrame。
import pandas as pd
import re
from collections import Counter
# 模拟DataFrame数据
data = {
'content': [
'My favorite fruit is mango. I like lichies too. I live in au. Cows are domistic animals.',
'I own RTX 4090...',
'There is political colfict between us and ca.',
'au, br mango, lichi apple,.... \n cat, cow, monkey donkey dogs'
]
}
df = pd.DataFrame(data)
print("原始DataFrame:")
print(df)
print("-" * 30)我们将关键词列表组织成一个字典,键为类别名称,值为该类别下的关键词列表。
labels = {
'fruits': ['mango', 'apple', 'lichi'],
'animals': ['dog', 'cat', 'cow', 'monkey'],
'country': ['us', 'ca', 'au', 'br'],
}
print("定义的关键词类别:")
for k, v in labels.items():
print(f" {k}: {v}")
print("-" * 30)这是核心逻辑部分。我们将创建一个名为calculate_probability的函数,它接受一个文本字符串和关键词类别字典作为输入,返回概率最高的类别标签。
def calculate_probability(text, labels_dict):
"""
计算给定文本中各关键词类别的概率,并返回概率最高的类别标签。
Args:
text (str): 输入的文本字符串。
labels_dict (dict): 包含关键词类别的字典,键为类别名,值为关键词列表。
Returns:
str: 概率最高的类别标签,如果所有概率均为0则返回 'NaN'。
"""
# 1. 文本预处理:提取单词并转换为小写
# re.findall(r'\b\w+\b', ...) 匹配所有独立的单词(字母数字下划线),
# \b 是单词边界,确保 'apples' 不会匹配 'apple',而是提取 'apples' 作为一个完整的词。
words = re.findall(r'\b\w+\b', str(text).lower())
word_count = len(words)
# 如果文本为空或没有提取到单词,则无法计算概率
if word_count == 0:
return 'NaN'
# 2. 词频统计:使用 collections.Counter 高效统计单词出现次数
counts = Counter(words)
# 3. 计算每个类别的概率
probs = {}
for category, keywords in labels_dict.items():
# 统计当前类别所有关键词在文本中的总出现次数
category_keyword_count = sum(counts[word] for word in keywords)
# 计算概率
probs[category] = category_keyword_count / word_count
# 4. 找出概率最高的类别
# 使用 max 函数配合 key 参数,找到字典中值最大的键
max_label = max(probs, key=probs.get)
# 5. 返回结果:如果最高概率大于0,则返回标签,否则返回 'NaN'
return max_label if probs[max_label] > 0 else 'NaN'最后,使用Pandas的apply方法将上述函数应用到DataFrame的content列,生成新的label列。
# 应用函数到 'content' 列
# 注意:apply 函数默认会将 Series 的每个元素作为第一个参数传递给函数。
# 额外的参数(如 labels_dict)可以通过关键字参数传递。
df['label'] = df['content'].apply(calculate_probability, labels_dict=labels)
print("处理后的DataFrame:")
print(df)输出结果:
原始DataFrame:
content
0 My favorite fruit is mango. I like lichies too...
1 I own RTX 4090...
2 There is political colfict between us and ca.
3 au, br mango, lichi apple,.... \n cat, cow, mo...
------------------------------
定义的关键词类别:
fruits: ['mango', 'apple', 'lichi']
animals: ['dog', 'cat', 'cow', 'monkey']
country: ['us', 'ca', 'au', 'br']
------------------------------
处理后的DataFrame:
content label
0 My favorite fruit is mango. I like lichies too... fruits
1 I own RTX 4090... NaN
2 There is political colfict between us and ca. country
3 au, br mango, lichi apple,.... \n cat, cow, mo... animals解释:
以上就是Pandas文本分类:基于关键词概率的高效标签识别教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号