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

Pandas分组后查找每组首个大于等于组均值的元素的索引

实现方法

你可以直接对SeriesGroupBy对象调用apply方法,自定义函数匹配对应组的均值后取符合条件的首个元素索引即可,代码如下:

1. 返回原DataFrame的全局索引

def get_first_match_index(s):
    # 取当前分组对应的均值
    mean_val = group_mean[s.name]
    # 筛选所有>=均值的元素,返回第一个的原索引
    return s[s >= mean_val].index[0]

# 执行计算,返回结果为索引是分组key、值为对应目标索引的Series
result = group.apply(get_first_match_index)

2. 返回分组内的相对位置索引(如你的示例中返回3的场景)

如果需要的是元素在分组内从0开始计数的位置,修改自定义函数即可:

def get_first_match_pos(s):
    mean_val = group_mean[s.name]
    # 布尔序列中首个True的位置即为目标
    return (s >= mean_val).argmax()

result = group.apply(get_first_match_pos)

验证示例

以你给出的测试场景为例,构造测试数据验证:

import pandas as pd
df = pd.DataFrame({
    'A': ['test', 'test', 'test', 'test', 'test', 'test'],
    'B': [5, 3, 7, 9, 1, 10]
})
group_mean = df.groupby('A').B.agg('mean')
# 手动将均值设为你示例中的8
group_mean['test'] = 8
group = df.groupby('A').B

print(group.apply(get_first_match_pos))
# 输出结果为 test    3,和你预期完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:33:01