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

如何处理DataFrame重复行:Product1与Product2同时重复时保留最小价格

问题解决:筛选Product1和Product2重复组中价格最小的行

示例数据

根据你提供的DataFrame,构造示例数据如下:

Product1Product2Price
AB10
AB5
CD8
CE12
CE7

期望输出

Product1Product2Price
AB5
CD8
CE7

解决方案

方法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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:55:18