You need to enable JavaScript to run this app. 如何从DataFrame的POS词性标注列提取前1000个高频名词?
优惠活动
大模型
产品
解决方案
定价
更多

如何从DataFrame的POS词性标注列提取前1000个高频名词?

问题分析与解决

依赖模块

import pandas as pd
from nltk.tag import pos_tag
import re
from collections import defaultdict,Counter
from nltk.stem import WordNetLemmatizer
from datetime import datetime
from tqdm import tqdm
import numpy as np
import os
import nltk
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize,sent_tokenize

测试数据集结构

df = pd.DataFrame({'comments': ['Daniel is really cool',
                                'Daniel is the most',
                                'We had such a',
                                'Very professional operation',
                                'Lots of bookcases']})

已执行预处理逻辑

df['tokenized'] = df['comments'].apply(word_tokenize)
df['tagged'] = df['tokenized'].apply(pos_tag)
df['lower_tagged'] = df['tokenized'].apply(lambda lt: [word.lower() for word in lt]).apply(pos_tag)

待处理列格式说明

lower_tagged列每行存储的是当前评论分词、转小写、词性标注后的元组列表,示例如下:

0    [(daniel, NN), (is, VBZ), (really, RB), (cool,...
1    [(daniel, NN), (is, VBZ), (the, DT), (most, RBS)]
2         [(we, PRP), (had, VBD), (such, JJ), (a, DT)]
3    [(very, RB), (professional, JJ), (operation, NN)]
4            [(lots, NNS), (of, IN), (bookcases, NNS)]

需求

提取该列中所有词性以NN开头的名词,统计出现频率后返回出现次数最高的前1000个名词组成的列表,预期输出示例:

nouns = ['daniel', 'operation', 'bookcases', 'lots']

原有代码错误原因

  1. 第一个方案直接遍历lower_tag(即df['lower_tagged']这个Series),每次拿到的是一整行的元组列表,不是列表里的单个元组,判断t[1] == 'NN'自然不成立,返回空列表。
  2. 第二个方案把整个Series对象传给word_tokenize,该方法要求输入字符串,所以抛出类型错误。

正确实现代码

# 收集所有符合要求的名词
all_nouns = []
for tag_list in df['lower_tagged']:
    for word, pos in tag_list:
        if pos.startswith('NN'):
            all_nouns.append(word)

# 统计频次,取前1000个
noun_counter = Counter(all_nouns)
top_1000_nouns = [word for word, cnt in noun_counter.most_common(1000)]

如果要写更简洁的pandas风格代码,可以用:

top_1000_nouns = [
    word for word, cnt in Counter(
        df['lower_tagged']
        .explode()
        .apply(lambda x: x[0] if x[1].startswith('NN') else pd.NA)
        .dropna()
    ).most_common(1000)
]

运行后输出的top_1000_nouns和预期结果一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 10:27:07