如何处理DataFrame重复行:Product1与Product2同时重复时保留最小价格
问题解决:筛选Product1和Product2重复组中价格最小的行
示例数据
根据你提供的DataFrame,构造示例数据如下:
| Product1 | Product2 | Price |
|---|---|---|
| A | B | 10 |
| A | B | 5 |
| C | D | 8 |
| C | E | 12 |
| C | E | 7 |
期望输出
| Product1 | Product2 | Price |
|---|---|---|
| A | B | 5 |
| C | D | 8 |
| C | E | 7 |
解决方案
方法1:使用groupby + idxmin
通过分组找到每组价格最小的行索引,再提取对应行:
import pandas as pd # 构造示例数据 df = pd.DataFrame({ 'Product1': ['A', 'A', 'C', 'C', 'C'], 'Product2': ['B', 'B', 'D', 'E', 'E'], 'Price': [10, 5, 8, 12, 7] }) # 按Product1和Product2分组,获取每组Price最小的行索引 min_price_idx = df.groupby(['Product1', 'Product2'])['Price'].idxmin() # 提取目标行并重置索引 result = df.loc[min_price_idx].reset_index(drop=True) print(result)
方法2:排序后去重
先按分组列和价格升序排序,再保留每组第一行:
import pandas as pd df = pd.DataFrame({ 'Product1': ['A', 'A', 'C', 'C', 'C'], 'Product2': ['B', 'B', 'D', 'E', 'E'], 'Price': [10, 5, 8, 12, 7] }) # 按Product1、Product2分组,再按Price升序排序 sorted_df = df.sort_values(by=['Product1', 'Product2', 'Price']) # 去重,保留每组第一行(即价格最小的行) result = sorted_df.drop_duplicates(subset=['Product1', 'Product2'], keep='first') print(result)
两种方法都能得到期望的输出,可根据个人习惯选择。
内容的提问来源于stack exchange,提问作者Mathew John
相关产品推荐
相关产品推荐

