如何将DataFrame中多列评论压缩为单个'good'/'bad'标签?
如何将DataFrame中的多列评论压缩为'good'/'bad'标签?
嘿,我来帮你搞定这个DataFrame评论压缩的需求,步骤很清晰,咱们一步步来:
首先,先把你提供的原始DataFrame用代码还原出来:
import pandas as pd dataframe1 = pd.DataFrame({ 'Product': ['P10', 'P11', 'P12', 'P13', 'P14', 'P15', 'P16', 'P17', 'P18', 'P19', 'P20'], 'comment1': ['not fresh', 'Quality is good', 'got banned', 'just got expired', 'nice product', 'very bad', 'limited stock', '0', 'very expensive', 'shinny', '0'], 'comment2': ['0', 'comparatively cheap', '1 year ago', '0', 'good customer satisfaction', '0', 'high demand', '0', 'bad quality', '0', 'always in stock'], 'comment3': ['short life time', 'nice product', 'was not that good demand is poor', 'no demand at all', '0', 'affects health of user', '0', 'high customer satisfaction', '0', 'cheap', 'most searched product'] })
你的核心需求是:
将每个产品的所有评论压缩为单个'good'或'bad'标签。若评论包含负面词汇('not fresh'、'short life'、'banned'、'not good'、'expired'、'no demand'、'bad'、'very expensive'),则标记为'bad';若包含正面词汇('high satisfaction'、'nice'、'cheap'、'shinny'),则标记为'good'。
实现方案
1. 先定义正负词汇集合
把需求里的关键词整理成两个集合,方便后续快速匹配:
# 负面词汇集合,覆盖你提到的所有负面关键词 negative_words = {'not fresh', 'short life', 'banned', 'not good', 'expired', 'no demand', 'bad', 'very expensive'} # 正面词汇集合,覆盖所有正面关键词 positive_words = {'high satisfaction', 'nice', 'cheap', 'shinny'}
2. 编写评论分类函数
写一个自定义函数,用来处理每一行的评论内容:
def classify_comments(row): # 把三个评论列的内容合并成一个字符串,同时过滤掉代表无评论的'0' all_comments = ' '.join([str(row['comment1']), str(row['comment2']), str(row['comment3'])]).replace('0', '') # 优先检查负面词汇:只要有一个负面关键词存在,直接标记为'bad' for word in negative_words: if word in all_comments: return 'bad' # 再检查正面词汇:只要有一个正面关键词存在,标记为'good' for word in positive_words: if word in all_comments: return 'good' # 兜底处理:如果既没有负面也没有正面词汇(案例里没这种情况,留个保险) return 'neutral'
3. 应用函数生成结果
用apply方法把函数作用到每一行,然后提取需要的列:
# 生成新的squeezed_comment列 dataframe1['squeezed_comment'] = dataframe1.apply(classify_comments, axis=1) # 只保留Product和squeezed_comment列,得到最终结果 result_df = dataframe1[['Product', 'squeezed_comment']] # 打印看看结果 print(result_df)
最终输出结果
运行上面的代码后,就会得到你期望的结果:
Product squeezed_comment 0 P10 bad 1 P11 good 2 P12 bad 3 P13 bad 4 P14 good 5 P15 bad 6 P16 bad 7 P17 good 8 P18 bad 9 P19 good 10 P20 good
小说明
这里优先检查负面词汇的原因是:如果某个产品的评论同时包含正负关键词(虽然你的案例里没有这种情况),按照需求逻辑应该优先标记为'bad',符合常规的负面优先判定规则。
内容的提问来源于stack exchange,提问作者Temp_coder
相关产品推荐
相关产品推荐

