创建Pivot Table在pandas数据框上失败

2024-09-28 01:28:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有列yearmonthsource。。。每个(年、月、源)有多个记录,我需要生成一个透视表,其索引是(年、月),源是列,每个(年、月、源)记录的计数是值。我有以下代码

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

怎么了?你知道吗


Tags: columns数据代码sourcedfsizeindexnp
1条回答
网友
1楼 · 发布于 2024-09-28 01:28:51

通过使用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

相关问题 更多 >

    热门问题