Python 在数据帧上创建pivot_表失败

Python 在数据帧上创建pivot_表失败,python,pandas,pivot-table,Python,Pandas,Pivot Table,我有一个数据框,其中包含年,月,源。。。每(年、月、源)有多个记录,我需要生成一个透视表,其索引为(年、月),源为列,每(年、月、源)记录的计数为值。我有以下代码 df.privot_table(index = ['year','month'], columns = ['source'], aggfunc = np.size, fill_value = 0) 下面是我的数据的样子 2001,02,A, .... 2001,02,A,.... 2001,03,B,.... 2001,03,B,.

我有一个数据框,其中包含
。。。每(年、月、源)有多个记录,我需要生成一个透视表,其索引为(年、月),源为列,每(年、月、源)记录的计数为值。我有以下代码

df.privot_table(index = ['year','month'], columns = ['source'], aggfunc = np.size, fill_value = 0)
下面是我的数据的样子

2001,02,A, ....
2001,02,A,....
2001,03,B,....
2001,03,B,....
2001,03,B,....
这就是我想要的数据

           A  B
2001, 02,  2, 0
2001, 03,  0, 3
但它会抛出以下错误消息

 Reindexing only valid with uniquely values index objects

有什么问题吗?

您可以使用
aggfunc=len
获得所需的输出

import pandas as pd

df = pd.DataFrame([[2001, '02', 'A'], [2001, '02', 'A'], [2001, '03', 'B'],
                   [2001, '03', 'B'], [2001, '03', 'B']],
                  columns=['Year', 'Month', 'Source'])

res = df.pivot_table(index=['Year', 'Month'], columns='Source',
                     aggfunc=len, fill_value=0)

print(res)

Source      A  B
Year Month      
2001 02     2  0
     03     0  3

您能否提供生成此错误的数据和代码?我无法按此问题中的描述复制您的问题。编辑我的原始帖子看起来可能是(1)您复制粘贴了我答案中的代码时出错,或者(2)您的数据与此处的数据不可比。如果(2),你可以用我的答案中的数据来回答你的问题。这只是我的数据样本……我不能显示整个表格。但是当我按(年、月、源)分组时,它看起来很好。@H.Z.,对不起,我无法解决一个我看不见的问题。你知道我收到此错误消息的原因吗?应用pivot_表后,应该有唯一的索引