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

如何对带MultiIndex的pandas Series执行位置索引,获取card分组第n个city项

解决方案

核心方法:使用groupby.nth()实现分组位置索引

pandas的groupby对象提供的nth(n)方法可以直接提取每个分组内第n个位置的条目,完美适配你的需求,且pandas-1.3.2版本完全支持该语法。

基础用法示例

你的Series第一层索引为card,直接按level='card'分组后调用nth()即可:

# 提取每个card分组下第0位(排名第一)的条目
res = s.groupby(level='card').nth(0)

执行后输出结果如下,默认保留完整多层索引:

card  city
c1    t1    0.500000
c2    t2    0.666667
Name: city, dtype: float64

提取第n位调整方式

需要提取其他位置时,只需修改nth()的入参即可,比如提取每个分组下第1位(第二位)条目:

res = s.groupby(level='card').nth(1)

输出结果:

card  city
c1    t2    0.250000
c2    t1    0.333333
Name: city, dtype: float64

注意事项

  • 如果你的Series还没有按照分组内的值从高到低排序,需要先完成组内排序再提取位置,避免取到的条目不符合排名要求:
# 先按card分组,组内按值降序排序
s_sorted = s.groupby(level='card', group_keys=False).apply(lambda x: x.sort_values(ascending=False))
# 再提取第0位
res = s_sorted.groupby(level='card').nth(0)
  • 提示:如果某card分组下的条目数少于n+1,nth(n)会自动跳过该分组,无匹配结果时返回空Series。

扩展场景:提取每个分组前k位

如果需要取前多个条目,直接用groupby.head(k)即可:

# 提取每个card分组前2位的条目
res = s.groupby(level='card').head(2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:06:04