Python Pandas 数据透视表存在边距问题 : got "Grouper for ' something' not 1-dimensional"

标签 python pandas pivot-table margins

我正在使用 df 和一个简单的数据透视表,我的目的是添加边距。 一切正常,直到我添加参数“margins=True”。

这是我的代码:

df1=pd.DataFrame({'brand':['A','A','A','A','A','B','A','B','A','B','B','A','A'],
'type':['C','C','C','C','C','C','C','C','D','D','C','C','C'],
'Year':[2022,2022,2022,2022,2022,2022,2022,2022,2022,2022,2022,2022,2022],
'Month':[9,9,9,8,9,9,9,9,8,10,9,10,10]})
table_1 = pd.pivot_table(df1, values = 'type', index = ['brand','type'],
columns = ['Year','Month'], aggfunc = {'type':len}, fill_value = '0', margins=True)

print(table_1)

我收到错误:“ValueError:‘类型’的石斑鱼不是一维的”

您有什么想法让它发挥作用吗?

谢谢

我尝试更改 aggfunc 的参数,我没有看到我在这里缺少什么...没有边距,结果很好。我只需要每行和每列的总和,这就是边距应该做的...

最佳答案

我认为您不喜欢同时使用 type 作为索引和值。解决方法是使用虚拟列:

table_1 = pd.pivot_table(df1.assign(val=1), 
                         values='val', index=['brand','type'],
                         columns=['Year','Month'], aggfunc={'val':len},
                         fill_value=0, margins=True)

print(table_1)

输出:

Year       2022       All
Month         8  9 10    
brand type               
A     C       1  5  2   8
      D       1  0  0   1
B     C       0  3  0   3
      D       0  0  1   1
All           2  8  3  13

注意。使用 fill_value=0 避免使用对象数据类型。

关于Python Pandas 数据透视表存在边距问题 : got "Grouper for ' something' not 1-dimensional",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74607735/

相关文章:

python - 如何检索函数或方法的异常列表

python - 在 fedora 13 中安装适用于 python3 的 Numpy

python - Django:使用表单的一个模板中的多个模型

python - Pandas 安装需要 NumPy 1.6.1

php - 尝试在 Resource Laravel 中返​​回数据透视表数据

Python pandas 部分折叠二维矩阵

python - HTML 结构转化为网络图

python - 如果列名 == Year 且值为 NaN pandas,则将数据框中的值向左移动

excel - 切片器正在更改我的数据透视表的行高?

python - Pandas Group 然后滚动和求和得到错误的结果