Pandas pivot 给出 ValueError

Pandas pivot gives ValueError

我有一个简单的数据框:

     category cnt customer_id
0       GIFTS   1       69683
1      LADIES   3      100526
2      LADIES   2      161139
3      LADIES   2      212455
4  HOME D?COR   1      133464

我正在尝试按计数旋转它:

df = df.pivot('customer_id', 'category', 'cnt')

但是报错:

ValueError: Shape of passed values is (15, 141016), indices imply (164611, 141016)

数据框中可能有 15 个类别和 164611 行,但我不确定为什么这是个问题?

您必须使用pivot_table函数:

df = pd.pivot_table(df, index='customer_id', columns='category', values='cnt')

并确保类型为数字:

df = pd.DataFrame(data, dtype=float)