Pandas如何重构函数将提取结果存入列表而非直接应用到DataFrame
问题背景
你有如下结构的DataFrame:
import pandas as pd df = pd.DataFrame({ 'text':['the weather is nice though', 'How are you today','the beautiful girl and the nice boy'], 'pos':["['DET', 'NOUN', 'VERB','ADJ', 'ADV']","['QUA', 'VERB', 'PRON', 'ADV']", "['DET', 'ADJ', 'NOUN','CON','DET', 'ADJ', 'NOUN' ]"] })
你需要实现不需要df.apply的函数,直接将pos为ADJ的对应词汇、索引追加到外部列表list_word_index中。
解决方案
你原有代码里的嵌套循环存在逻辑问题:分别遍历text列和pos列会导致词和词性错位,需要逐行匹配同一条数据的text和pos内容,修改后的完整代码如下:
方案1:每条ADJ匹配结果单独存为字典存入列表
import ast list_word_index = [] def extract_words(dataframe): # 逐行配对同一条数据的分词结果和pos列表 for text_splited, pos_str in zip(dataframe.text.str.split(), dataframe.pos): pos_list = ast.literal_eval(pos_str) for i, p in enumerate(pos_list): if p == 'ADJ': word_index_pair = {text_splited[i]: i} list_word_index.append(word_index_pair) extract_words(df)
运行后list_word_index输出结果为:
[{'nice': 3}, {'beautiful': 1}, {'nice': 5}]
方案2:每行的所有ADJ结果合并为一个字典存入列表(和原apply逻辑输出格式完全一致)
import ast list_word_index = [] def extract_words(dataframe): for text_splited, pos_str in zip(dataframe.text.str.split(), dataframe.pos): word_pos = {} pos_list = ast.literal_eval(pos_str) for i, p in enumerate(pos_list): if p == 'ADJ': word_pos[text_splited[i]] = i list_word_index.append(word_pos) extract_words(df)
运行后list_word_index输出结果为:
[{'nice': 3}, {}, {'beautiful': 1, 'nice': 5}]
内容的提问来源于stack exchange,提问作者zara kolagar
相关产品推荐
相关产品推荐

