在Pandas中按Plant、Material组获取最小scale_qty对应的quota
解决方案
方法1:利用idxmin获取索引后映射
先通过分组找到每组中scale_qty最小的行的索引,再提取对应quota值并映射到原DataFrame:
# 获取每组scale_qty最小的行的索引 min_scale_idx = df.groupby(['plant', 'material'])['scale_qty'].idxmin() # 构建plant+material到对应quota的映射表 quota_map = df.loc[min_scale_idx].set_index(['plant', 'material'])['quota'] # 匹配到原表生成新列 df['min_scale_quota'] = df.set_index(['plant', 'material']).index.map(quota_map) # 恢复原索引(可选) df = df.reset_index(drop=True)
方法2:排序后分组取首行
先按分组字段和scale_qty升序排序,取每组第一行的quota再合并回原表:
# 排序后分组提取最小scale_qty对应的quota min_quota_df = df.sort_values(['plant', 'material', 'scale_qty'])\ .groupby(['plant', 'material'])\ .first()[['quota']]\ .rename(columns={'quota': 'min_scale_quota'}) # 合并回原DataFrame df = df.merge(min_quota_df, on=['plant', 'material'], how='left')
方法3:transform结合自定义逻辑
适合小数据集,直接在分组内定位最小scale_qty对应的quota:
df['min_scale_quota'] = df.groupby(['plant', 'material']).apply( lambda x: x['quota'][x['scale_qty'] == x['scale_qty'].min()].iloc[0] ).reset_index(level=[0,1], drop=True)
注意事项
- 若每组存在多个相同的最小
scale_qty,上述方法默认取第一个出现的quota;如需处理这种场景,可修改逻辑,比如将iloc[0]替换为mean()(取均值)或','.join()(拼接所有值)。 - 大数据集优先选用方法1或2,执行效率更高。
内容的提问来源于stack exchange,提问作者Notme2104
相关产品推荐
相关产品推荐

