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

Python按条件筛选DataFrame:保留同一org_uniq_nr下founder_rank最小值行

筛选每个组织唯一编号下创始人排名最小的行

原数据集

org_nameorg_uniq_nrfounder_rankfounder_nameamount_money
Zoho65246n1m1
Zoho6522389n2m2
a19011299n3m3
b88776n4m4
c6965991n5m5
b8880n6m6
Zoho7791445n7m7

需求说明

按org_uniq_nr(组织唯一编号)分组,保留每组中founder_rank值最小的行,删除同编号下排名更高的行。注:期望结果中Zoho的org_uniq_nr应为652而非106,属于笔误。


解决方法

1. Python Pandas 实现

通过分组后取最小值对应的行索引来筛选:

import pandas as pd

# 构造原数据
data = {
    'org_name': ['Zoho', 'Zoho', 'a', 'b', 'c', 'b', 'Zoho'],
    'org_uniq_nr': [652, 652, 1901, 88, 6965, 88, 779],
    'founder_rank': [46, 2389, 1299, 776, 991, 80, 1445],
    'founder_name': ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7'],
    'amount_money': ['m1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7']
}
df = pd.DataFrame(data)

# 分组获取每个org_uniq_nr下founder_rank最小的行
result_df = df.loc[df.groupby('org_uniq_nr')['founder_rank'].idxmin()]

# 重置索引(可选操作)
result_df = result_df.reset_index(drop=True)

print(result_df)

执行后输出结果:

org_nameorg_uniq_nrfounder_rankfounder_nameamount_money
Zoho65246n1m1
a19011299n3m3
b8880n6m6
c6965991n5m5
Zoho7791445n7m7

2. SQL 实现

使用窗口函数ROW_NUMBER()对分组内的行按排名排序,取排名第一的行:

SELECT org_name, org_uniq_nr, founder_rank, founder_name, amount_money
FROM (
    SELECT 
        *,
        ROW_NUMBER() OVER (PARTITION BY org_uniq_nr ORDER BY founder_rank ASC) AS row_num
    FROM org_founder_data
) ranked_data
WHERE row_num = 1;

若存在同一编号下多个行founder_rank并列最小的情况,可将ROW_NUMBER()替换为RANK(),以保留所有并列最小的行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 07:13:13