如何在R语言中合并相似数据行并按规则聚合数值?
问题解决:合并同项目不同版本的DataFrame数据
需求说明
需要将DataFrame中同一项目的不同版本(如googleV1与googleV2)合并,按以下规则聚合:
quantity、revenue字段求和rating字段求平均- 保留
group列作为分组维度,最终每个项目-分组组合仅保留一行 - 要求支持多分组列场景,且通过列序号引用需聚合的字段
原始数据集
| item | group | quantity | revenue | rating |
|---|---|---|---|---|
| googleV1 | blue | 4525 | $523513 | 94% |
| googleV2 | blue | 2452 | $134134 | 82% |
| 123V5 | red | 3563 | $134134 | 82% |
| 123V6 | red | 34534 | $2345 | 34% |
| 123V7 | yellow | 4574 | $34535 | 64% |
期望输出
| item | group | quantity | revenue | rating |
|---|---|---|---|---|
| blue | 6977 | $657647 | 88% | |
| 123 | red | 38097 | $136479 | 58% |
| 123 | yellow | 4574 | $34535 | 64% |
解决方案(Python Pandas)
import pandas as pd # 1. 创建原始DataFrame data = { 'item': ['googleV1', 'googleV2', '123V5', '123V6', '123V7'], 'group': ['blue', 'blue', 'red', 'red', 'yellow'], 'quantity': [4525, 2452, 3563, 34534, 4574], 'revenue': ['$523513', '$134134', '$134134', '$2345', '$34535'], 'rating': ['94%', '82%', '82%', '34%', '64%'] } df = pd.DataFrame(data) # 2. 预处理:转换数值型字段格式(去掉$、%符号) df['revenue_num'] = df['revenue'].str.replace('$', '').astype(int) df['rating_num'] = df['rating'].str.replace('%', '').astype(int) # 3. 提取项目核心名称(去掉版本号Vx部分) df['item_core'] = df['item'].str.extract(r'^(.*?)V') # 处理无版本号的情况(如果存在) df['item_core'] = df['item_core'].fillna(df['item']) # 4. 分组聚合:按列序号引用字段,支持多分组列 # 列序号说明:quantity是第2列(索引从0开始),revenue_num是第5列,rating_num是第6列 agg_result = df.groupby(['item_core', 'group']).agg( quantity=(df.iloc[:, 2], 'sum'), revenue_sum=(df.iloc[:, 5], 'sum'), rating_avg=(df.iloc[:, 6], 'mean') ).reset_index() # 5. 还原格式:添加$和%符号 agg_result['revenue'] = '$' + agg_result['revenue_sum'].astype(str) agg_result['rating'] = agg_result['rating_avg'].astype(int).astype(str) + '%' # 6. 整理最终输出列 final_df = agg_result[['item_core', 'group', 'quantity', 'revenue', 'rating']].rename(columns={'item_core': 'item'}) # 打印结果 print(final_df)
关键说明
- 多分组支持:若需添加更多分组列,只需在
groupby的列表中加入对应列名即可(如groupby(['item_core', 'group', 'new_group_col'])) - 版本号提取逻辑:使用正则
^(.*?)V匹配V前的所有字符作为项目核心名称,若存在无版本号的item,会自动填充原始item值。
内容的提问来源于stack exchange,提问作者piper180
相关产品推荐
相关产品推荐

