我有一个数据透视表(pt),如下所示:
+---------+------------+-------+----+
| | ZY | z | y |
+---------+------------+-------+----+
| period_s| ZONE | | |
+---------+------------+-------+----+
| 201901 | A | 14 | 34 |
| | B | 232 | 9 |
| | C | 12 | 2 |
+---------+------------+-------+----+
| 201902 | A | 196 | 70 |
| | K | 10 | 1 |
| | D | 313 | 99 |
+---------+------------+-------+----+
使用以下代码来自数据帧(df):
pt=df.pivot_table(index=['period_s','ZONE'], columns='ZY', values='ID', aggfunc="count")
其中ZY字段具有z和y两个类。
我尝试使用
df = table.reset_index()
也
df.columns = df.columns.droplevel(0) #remove amount
df.columns.name = None #remove categories
df = df.reset_index()
如此处transform pandas pivot table to regular dataframe所述,Convert pivot tables to dataframe就是这样
我想要一个这样的数据框:
+---------+-------+------------+----------+
| period_s| ZONE | z | y |
+---------+-------+------------+----------+
| 201901 | A | 14 | 34 |
| 201901 | B | 232 | 9 |
| 201901 | C | 12 | 2 |
| 201902 | A | 196 | 70 |
| 201902 | K | 10 | 1 |
| 201902 | D | 313 | 99 |
+---------+-------+------------+----------+
谢谢