Skip to main content
 首页 » 编程设计

python之Pandas groupby 和转换 ('count' ) 给出放置错误之在较小的数据集上工作正常

2024年10月24日10mfryf

Pandas 中真正简单的任务是抛出一个我不明白的错误。使用像这样的简单数据集:

test=pd.DataFrame([[1,3],[1,6],[2,4],[3,9],[3,2]],columns=['a','b']) 

我可以执行以下命令来计算一个值出现在测试的“a”列中的次数。

test['count']=test.groupby('a').transform('count') 

这会产生:

>>> test 
       a  b  count 
    0  1  3      2 
    1  1  6      2 
    2  2  4      1 
    3  3  9      2 
    4  3  2      2 

完美。但是根据我的真实数据,这是行不通的。这是我的一小段数据,可用于重现问题:

newtest=pd.DataFrame([['010010201001000','001','0220','AL','0'],['010010201001001','001','0220','AL','0'],['010010201001002','001','0220','AL','0'],['010010201001003','001','0160','AL','0'],['010010201001004','001','0160','AL','0']],columns=['BlockID','CountyFP','District','state_x','HD']) 
newtest['blocks']=newtest.groupby(['CountyFP','District','state_x']).transform('count') 

尝试这给了我这个错误:

ValueError: Wrong number of items passed 2, placement implies 1 

我真的不明白是什么让我的“真实”示例与游戏集有什么不同,谷歌搜索此错误会产生其他错误示例,但我仍然不清楚为什么会在此处生成它。

更令人困惑的是,如果我只执行上面代码的右侧,它工作正常 - 生成每列都有计数的 newtest。所以这就像作业给它带来了问题。

请您参考如下方法:

您没有选择任何列来执行聚合,所以它在剩余的 2 列上执行聚合,如果您选择其中一列,那么您将获得所需的结果:

In [6]: 
newtest['blocks'] = newtest.groupby(['CountyFP','District','state_x'])['BlockID'].transform('count') 
newtest 
 
Out[6]: 
           BlockID CountyFP District state_x HD  blocks 
0  010010201001000      001     0220      AL  0       3 
1  010010201001001      001     0220      AL  0       3 
2  010010201001002      001     0220      AL  0       3 
3  010010201001003      001     0160      AL  0       2 
4  010010201001004      001     0160      AL  0       2 

你的尝试输出:

In [9]: 
newtest.groupby(['CountyFP','District','state_x']).transform('count') 
 
Out[9]: 
   BlockID  HD 
0        3   3 
1        3   3 
2        3   3 
3        2   2 
4        2   2 

您可以看到它生成了 2 列,因为这些是剩余的列,因此是您观察到的错误消息。