如何合并pandas DataFrame中col1与col2互换的行并对count列求和
Pandas 合并col1、col2互为排列的行实现方法
核心思路是为每对col1、col2生成唯一的分组标识,确保互换的两个值对应同一个分组,分组后保留首次出现的col1、col2顺序,同时对count列求和即可。
实现代码(小规模数据适用,写法直观)
import pandas as pd # 构造示例输入数据 df = pd.DataFrame({ 'col1': ['A', 'C', 'B', 'E', 'G', 'D', 'I'], 'col2': ['B', 'D', 'A', 'F', 'H', 'C', 'J'], 'count': [3, 2, 5, 2, 8, 5, 4] }) # 生成分组键:将col1、col2排序后转为元组,互换值的行生成的键完全一致 df['group_key'] = df.apply(lambda x: tuple(sorted([x['col1'], x['col2']])), axis=1) # 分组聚合:保留首次出现的col1、col2,count列求和,sort=False保证原顺序不变 result = df.groupby('group_key', as_index=False, sort=False).agg({ 'col1': 'first', 'col2': 'first', 'count': 'sum' }).drop('group_key', axis=1) print(result)
高性能实现(适合十万行以上的大数据量,向量化操作速度更快)
不需要逐行apply,用numpy的逐元素比较生成分组键,效率提升明显:
import pandas as pd import numpy as np df = pd.DataFrame({ 'col1': ['A', 'C', 'B', 'E', 'G', 'D', 'I'], 'col2': ['B', 'D', 'A', 'F', 'H', 'C', 'J'], 'count': [3, 2, 5, 2, 8, 5, 4] }) # 向量化生成两个分组键,确保互换值的行key1、key2完全相同 df['key1'] = np.minimum(df['col1'], df['col2']) df['key2'] = np.maximum(df['col1'], df['col2']) result = df.groupby(['key1', 'key2'], as_index=False, sort=False).agg({ 'col1': 'first', 'col2': 'first', 'count': 'sum' }).drop(['key1', 'key2'], axis=1) print(result)
输出结果
两种方法得到的结果都和预期一致:
| col1 | col2 | count |
|---|---|---|
| A | B | 8 |
| C | D | 7 |
| E | F | 2 |
| G | H | 8 |
| I | J | 4 |
内容的提问来源于stack exchange,提问作者chuchu
相关产品推荐
相关产品推荐

