我正在使用 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/