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

Pandas中用for循环和.append给嵌套列表赋值时遇索引错误求助

解决DataFrame分组生成嵌套坐标列表的索引错误问题

错误原因

你的错误根源在于row['MonthYear']是字符串类型(如Oct2020),直接执行row['MonthYear']-1既不符合语法(字符串无法与整数相减),也无法对应到points_months的列表索引,最终触发IndexError。


方案1:修正循环逻辑(保留原始思路)

先建立月份字符串到列表索引的映射,再通过映射获取正确索引填充数据:

# 获取唯一月份列表,保留原数据中的出现顺序
unique_months = pd.unique(XY_22225['MonthYear'])
# 创建月份到索引的映射字典
month_index_map = {month: idx for idx, month in enumerate(unique_months)}
# 初始化嵌套列表
points_months = [[] for _ in unique_months]

# 循环填充数据
for _, row in XY_22225.iterrows():
    current_point = (row['X'], row['Y'])
    # 通过映射获取当前月份对应的列表索引
    target_idx = month_index_map[row['MonthYear']]
    points_months[target_idx].append(current_point)

方案2:用pandas groupby实现更高效的分组(推荐)

无需手动循环,直接利用groupby按月份分组,批量生成坐标列表:

# 按MonthYear分组,生成每个月份的坐标元组列表(保持原数据的月份顺序)
points_months = [list(zip(group['X'], group['Y'])) for _, group in XY_22225.groupby('MonthYear', sort=False)]

如果需要按时间顺序排序分组,可以先将MonthYear转为datetime类型:

# 将字符串格式的月份转为datetime类型
XY_22225['MonthYear'] = pd.to_datetime(XY_22225['MonthYear'], format='%b%Y')
# 按时间顺序分组生成坐标列表
points_months = [list(zip(group['X'], group['Y'])) for _, group in XY_22225.groupby('MonthYear', sort=True)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 06:07:08