python data_error ai_generated true

ValueError: 无法在具有重复标签的轴上重新索引

ValueError: cannot reindex on an axis with duplicate labels

ID: python/pandas-cannot-reindex-duplicate

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-09-11首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

对索引(或列)含重复标签的 DataFrame 调用 df.reindex()。重新索引需要唯一标签来映射旧位置到新位置。

English

df.reindex() called on a DataFrame whose index (or columns) contains duplicate labels. Reindex requires unique labels to map old positions to new ones.

generic

解决方案

  1. 90% 成功率
    df = df.loc[~df.index.duplicated(keep='first')]; df.reindex(new_index)
  2. 85% 成功率
    Aggregate first: df = df.groupby(level=0).sum(); df.reindex(new_index)

无效尝试

常见但无效的做法:

  1. 90% 失败

    Same error, duplicates still present

  2. 85% 失败

    Sorting doesn't dedupe