如何将DataFrame中的部分字段转换为向量,实现情感评分结构化处理
实现方法
直接用Python的pandas库即可完成转换,核心逻辑是按Group、User分组后,将情感类型的评论数展开为列,再组合为指定格式的向量:
import pandas as pd # 构造示例DataFrame,实际使用时替换为你自己的数据源即可 df = pd.DataFrame({ 'Group': ['G1', 'G1', 'G1', 'G2', 'G2', 'G2'], 'User': ['User1', 'User2', 'User2', 'User3', 'User3', 'User4'], 'Sentiment': ['positive', 'positive', 'negative', 'positive', 'negative', 'negative'], '#No of Reviews': [5,5,4,4,4,6] }) # 1. 按Group、User分组,把情感类型转为列、值对应评论数,缺失值自动填0 pivot_df = df.pivot_table( index=['Group', 'User'], columns='Sentiment', values='#No of Reviews', fill_value=0, aggfunc='sum' # 加这个参数可以兼容同一个分组下有重复情感类型的情况,自动求和 ).reset_index() # 2. 拼接positive、negative为指定顺序的向量 pivot_df['sentiment_vector'] = pivot_df.apply(lambda row: [row['positive'], row['negative']], axis=1) # 最终结果,只保留需要的字段 result = pivot_df[['Group', 'User', 'sentiment_vector']] print(result)
运行后输出结果和你要求的格式完全一致:
| Group | User | sentiment_vector |
|---|---|---|
| G1 | User1 | [5, 0] |
| G1 | User2 | [5, 4] |
| G2 | User3 | [4, 4] |
| G2 | User4 | [0, 6] |
- 如果需要调整向量中positive、negative的顺序,直接修改
apply里列表的元素顺序即可 - 转换后的向量可以直接取出供其他脚本调用
内容的提问来源于stack exchange,提问作者Vijaya
相关产品推荐
相关产品推荐

