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

如何在Pandas中将Pros、Cons文本列按对应情感值合并为Review列

Pandas DataFrame 结构调整实现方法

我们可以通过两种简洁的方式实现需求:

方法一:拆分拼接法

先分别提取pros和cons对应的子DataFrame,重命名列后按顺序拼接:

  1. 先构造示例测试数据:
import pandas as pd

df = pd.DataFrame({
    'pros': ['pro_text1', 'pro_text2'],
    'cons': ['con_text1', 'con_text2'],
    'sentiment': ['positive', 'negative']
})
  1. 拆分并拼接:
# 提取pros列并将列名改为review
pros_part = df[['pros', 'sentiment']].rename(columns={'pros': 'review'})
# 提取cons列并将列名改为review
cons_part = df[['cons', 'sentiment']].rename(columns={'cons': 'review'})
# 按先pros后cons的顺序拼接,重置索引避免重复
final_df = pd.concat([pros_part, cons_part], ignore_index=True)

方法二:melt转置法

利用melt将宽表转为长表,再调整顺序:

# 将pros和cons列转置为review列,保留sentiment作为关联字段
melted_df = df.melt(
    id_vars='sentiment',
    value_vars=['pros', 'cons'],
    value_name='review'
)
# 按原列名排序确保pros在前,删除多余列并重置索引
final_df = melted_df.sort_values('variable', ascending=True)\
                    .drop('variable', axis=1)\
                    .reset_index(drop=True)

运行后得到的final_df结构如下:

review sentiment
0  pro_text1  positive
1  pro_text2  negative
2  con_text1  positive
3  con_text2  negative

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:55:41