You need to enable JavaScript to run this app. 如何用Pandas按年份分组取组内相对索引对应的数组元素值
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas按年份分组取组内相对索引对应的数组元素值

问题实现方案

核心逻辑非常直接:你需要的索引i,本质是按year分组后、组内从0开始的连续行序号。由于原DataFrame已经提前按year、month排好序,不需要通过month列计算位置,直接用pandas内置的分组累计计数方法就能拿到正确的i值。之前误用.get_loc('month')的问题在于,这个方法是用于获取DataFrame的列索引位置,根本不是用来计算组内行顺序的,属于方法适用场景错配。

可直接运行的代码

import pandas as pd

# 复现你的原始数据
df = pd.DataFrame({
    'year': [2020, 2020, 2020, 2021, 2021, 2021, 2021],
    'month': [1, 2, 5, 2, 4, 7, 9],
    'values': [
        ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'],
        ['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D']
    ]
})

# 1. 生成分组内的位置索引i
group_pos = df.groupby('year').cumcount()
# 2. 按索引取出对应位置的元素,生成value列
df['value'] = [val_list[idx] for val_list, idx in zip(df['values'], group_pos)]

结果验证

运行上述代码后,输出的DataFrame完全匹配你的预期格式:

year  month               values value
0   2020      1          [a, b, c]     a
1   2020      2          [a, b, c]     b
2   2020      5          [a, b, c]     c
3   2021      2  [A, B, C, D]        A
4   2021      4  [A, B, C, D]        B
5   2021      7  [A, B, C, D]        C
6   2021      9  [A, B, C, D]        D

注意事项

  • 该方案生效的前提,就是你提到的「原DataFrame已经按year、month列排序」,如果后续没有提前排序,需要先执行df = df.sort_values(['year', 'month']).reset_index(drop=True)再取累计计数,否则组内顺序会乱,导致i值偏移。
  • 列表推导式的写法比.apply()的循环性能高很多,在大数据量场景下不会有明显的执行延迟。

内容的提问来源于stack exchange,提问作者L.B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 06:06:03