【发布时间】:2021-02-06 07:36:16
【问题描述】:
问题
我有一个类似于下面玩具示例的数据集。
我需要创建一个表格,将项目和期间的每个组合的值相加,并以交叉表/数据透视表格式显示。
如果我使用pandas.crosstab(),我会得到我想要的输出。
如果我使用 pandas.pivot_table,我会得到看起来像是多级索引的列。
如何去掉多级索引?
是的,我可以只使用crosstab,但是():
- 总的来说,我想了解多级索引
- 有时我 没有“原始”数据,我收到格式的数据 由 pivot_table 生成
我尝试过的
我试过totals_pivot_table.droplevel(0) 但它说只有一层。这是什么意思?
dataframe.columns.droplevel() 不再受支持
示例表
这是 pivot_table 的输出:
+--------+-------+-------+-------+-------+
| | value | value | value | value |
+--------+-------+-------+-------+-------+
| period | 1 | 2 | 3 | All |
| item | | | | |
| x | 10 | 11 | 12 | 33 |
| y | 13 | 14 | 15 | 42 |
| All | 23 | 25 | 27 | 75 |
+--------+-------+-------+-------+-------+
这是我需要的:
+------+----+----+----+-----+
| item | 1 | 2 | 3 | All |
+------+----+----+----+-----+
| x | 10 | 11 | 12 | 33 |
| y | 13 | 14 | 15 | 42 |
| All | 23 | 25 | 27 | 75 |
+------+----+----+----+-----+
玩具代码
df = pd.DataFrame()
df['item'] = np.repeat(['x','y'],3)
df['period'] = np.tile([1,2,3],2)
df['value'] = np.arange(10,16)
pivot = df.pivot(index ='item', columns ='period', values = None)
totals_pivot_table = df.pivot_table(index ='item', columns = 'period', aggfunc ='sum', margins = True)
totals_ct = pd.crosstab( df['item'], df['period'], values =df['value'] , aggfunc ='sum', margins=True)
【问题讨论】:
标签: python pandas dataframe pivot-table