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

Python实现分组内位置按顺序映射为location组的方法

解决方案

你需要在每个place_id分组内,基于现有position的顺序生成连续的location编号,以下是可行的步骤:

步骤1:将结果转换为DataFrame(便于操作)

你的filterd_df是一个多级索引的Series,先重置索引转为DataFrame,并给计数列命名:

# 重置索引,把多级索引转为列,计数列命名为counts
result_df = filterd_df.reset_index(name='counts')

步骤2:按place_id分组生成location编号

使用groupby结合cumcount(),在每个place_id组内按原有顺序生成从1开始的编号:

# cumcount()从0开始计数,加1得到从1开始的location编号
result_df['location'] = result_df.groupby('place_id').cumcount() + 1

步骤3:(可选)恢复多级索引格式

如果需要保持和原输出类似的结构,可重新设置多级索引:

final_result = result_df.set_index(['place_id', 'location'])['counts']

最终final_result的输出如下:

place_id  location
1         1          1234
          2          7000
          3          8000
          4         10000
2         1          4111
          2          9875
          3          9900
          4          1000
Name: counts, dtype: int64

为什么之前的尝试没成功?

大概率是直接在多级索引的Series上操作cumcount()时,没有正确指定分组层级。转为DataFrame后,按place_id列分组会更直观,不容易出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 18:37:15