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

标签 python pandas

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 列,因为这些是剩余的列,因此是您观察到的错误消息。

关于python - Pandas groupby 和转换 ('count' ) 给出放置错误 - 在较小的数据集上工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34841411/

相关文章:

python - 在 Pandas 数据帧上应用 Savitzky-Golay 过滤器

python - 在 SQLAlchemy 中使用临时表

python - 按列对python数组/recarray进行排序

python - python的字符串方法中%的转义字符是什么

python - Pandas DataFrame 按两列分组并获得第一个和最后一个

python - 具有不同阈值的 pandas 数据帧上的多个 if 条件

python - 在 Windows 上使用 Paho MQTT 库时如何指定证书颁发机构证书文件

python - Django admin 和 MongoDB,可能吗?

python - QTableWidget-自动公式驱动单元格

python-3.x - 如何将 Pandas 数据帧写入 HDF5 数据集