【问题标题】:Reshaping and Pivot Tables - ValueError: Index contains duplicate entries, cannot reshape重塑和数据透视表 - ValueError:索引包含重复条目,无法重塑
【发布时间】:2018-11-17 12:49:53
【问题描述】:

我的数据框df 具有以下结构:

product_id  url                 type
0   2013367 7405e0c483323f78b   A
1   2013367 ea919d2276f60f31e   B
2   452998  117312244aa203a03   A
3   452998  1a6a41a6141235d68   B
4   2196333 cd66f91431fbae2d4   A

我正在尝试使用 pandas pivot 函数来重组数据框,如下所示:

product_id   A                  B
2013367      7405e0c483323f78b  ea919d2276f60f31e   
452998       117312244aa203a03  1a6a41a6141235d68   
2196333      cd66f91431fbae2d4  NaN

按照文档(https://pandas-docs.github.io/pandas-docs-travis/reshaping.html)我使用df.pivot(index="product_id", columns="type",values='url')

但是,我收到以下错误:

ValueError:索引包含重复条目,无法重塑

我在这里 (How to pivot categorical variable in pandas?) 发现了一个类似的问题,其中解决方案涉及到日期时间格式的转换。但是,我没有使用日期作为索引。

我该如何解决这个问题?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    好的,我刚刚发现问题是由于我的数据集中存在与类型 A 关联多次的 product_id。像这样:

    product_id  url                 type
    0   2013367 7405e0c483323f78b   A
    1   2013367 ea919d2276f60f31e   B
    2   452998  117312244aa203a03   A < ---- same id and type but different url
    3   452998  1a6a41a6141235d68   A < ---- same id and type but different url
    4   2196333 cd66f91431fbae2d4   A
    

    因此,pandas 不知道要分配哪个值,导致出现上述错误。

    解决方案是在pivot 之前使用drop_duplicates,如下所示:df.drop_duplicates(subset=["product_id","type"],inplace=True)

    【讨论】:

      猜你喜欢
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-23
      • 2018-05-31
      • 1970-01-01
      • 2022-01-24
      • 2021-12-22
      相关资源
      最近更新 更多