我有数据帧,并使用命令 pd.pivot_table(df,columns="category",index=["year","period"])
在这个数据帧做了一些数据处理,我想逆转过程,以获得原始形成的DF.I尝试与 pd.melt
和 pd.wide_to_long
在pivot_table中,列是两个值的组合,类似于这样。("a", "1"),("a", "2"),("a", "3"),......。,("d", "5")其中第1位是原始数据框中的列,第2位是类别列的值。
原有的df cols。
year period category a b c d
1
2
3
4
5
pivot_table:
|a | b | ... | d
category |1 2 3 4 5 | 1 2 3 4 5 | ... | 1 2 3 4 5
year | period
>.我有数据框架,并使用命令 pd.pivot_table(df,columns="category",index=["year", "period"]。
data={"col1":[1111,1111,1111,1111,2222,2222,2222,2222],
"col2":["a1","a1","a1","a1","a2","a2","a2","a2"],
"col3":[1,2,1,2,1,2,1,2],"
"a":[555,555,555,555,555,555,555,555],
"b":[666,666,666,666,666,666,666,666]}
df=pd.DataFrame.from_dict(data)
table=pd.pivot_table(df,columns="col3",index=["col1","col2"])
一般来说,对于给定的从数据框架构造数据透视表的方式,两个不同的数据框架可能会产生相同的数据透视表。所以这个过程是不可逆的。例如,将以下内容与你的 df
和 table
:
data2 = {"col1": [1111, 1111, 2222, 2222],
"col2": ["a1", "a1", "a2", "a2"],
"col3": [1, 2, 1, 2],
"a": [555, 555, 555, 555],
"b": [666, 666, 666, 666]}
df2 = pd.DataFrame.from_dict(data2)
table2 = pd.pivot_table(df2, columns="col3", index=["col1", "col2"])
df2
与你的不同 df
但 table2
与你的 table
.
说到这里,如果你对你想从数据透视表中重建的数据框架的了解比单单从表中推断的要多,你也许可以写一个自定义函数来实现这些知识。
你在数据透视表中看到的双索引结构是pandas中一个特殊索引类的实例,叫做 MultiIndex
.