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

如何使用groupby与get_group提取pandas DataFrame指定product_id对应品牌

实现代码

import pandas as pd

# 构造原始数据集
catalog = {'product_id': [1, 2, 3, 1, 2, 4, 3, 5, 6],
        'brand_name': ['FW', 'GW', 'FK','FW','GW','WU','FK','MU', 'AS'],
        'product_class': ['ACCESSORIES', 'DRINK', 'FOOD', 'ACCESSORIES', 'DRINK', 'FURNITURE','FOOD', 'ELECTRONICS', 'APPAREL']}
df = pd.DataFrame(data=catalog)

prod = [1,3,4]

# 按product_id完成分组
pid_groups = df.groupby('product_id')

result = []
for pid in prod:
    # 提取对应product_id的分组
    current_group = pid_groups.get_group(pid)
    # 取分组内第一个brand_name值(同一product_id对应的brand_name一致)
    result.append({
        'Product_id': pid,
        'Brand_name': current_group['brand_name'].iloc[0]
    })

# 转换为目标DataFrame格式
result_df = pd.DataFrame(result)
print(result_df)

补充说明

如果需要输出的Brand_name字段带单引号,把取值行替换为f"'{current_group['brand_name'].iloc[0]}'"即可。该方案先一次性完成全表分组,后续匹配时直接通过分组索引定位数据,避免了重复遍历全表,数据量越大效率优势越明显。

内容的提问来源于stack exchange,提问作者user177196

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:45:10