Pandas - 创建重复索引列的数据透视表

Pandas - Creating pivot of duplicates index column

我正在尝试创建我的 Dataframe 的数据透视表,它没有数值并且索引列中存在重复项。下面是我的数据的样子:

sale_id, product, sale_date
101, ABC, 2021-01-01
101, DEF, 2021-02-01
101, XYZ, 2021-03-01
101, KLM, 2021-01-04

预期以下输出:

    ABC, DEF, XYZ, KLM
101 2021-01-01, 2021-02-01, 2021-03-01, 2021-01-04

我尝试了以下

df.pivot(index='sale_id', columns='product', values='sale_date')

它抛出以下错误

ValueError: Index contains duplicate entries, cannot reshape

I am trying to create a pivot of my Dataframe that has no numerical values and duplicates exist in the index column.

对于测试重复使用 DataFrame.duplicated:

df1 = df[df.duplicated(['sale_id','product'], keep=False)]
print (df1)

要删除重复项,请使用 DataFrame.drop_duplicates:

(df.drop_duplicates(['sale_id','product'])
   .pivot(index='sale_id', columns='product', values='sale_date'))