如何将Pandas DataFrame的索引设置为二级列表头并重组数据?
Pandas将DataFrame索引转换为二级列头
原始DataFrame(df1)
以下是原始数据的定义及输出:
import pandas as pd data1 = [['a', 'b', 'c'], [1, 2, 3], [1, 0, 0], [0, 1, 0]] columns1 = ['c0', 'c1', 'c2'] index1 = ['i0', 'i1', 'i2', 'i3'] df1 = pd.DataFrame(data1, columns=columns1, index=index1) print(df1)
输出结果:
c0 c1 c2 i0 a b c i1 1 2 3 i2 1 0 0 i3 0 1 0
目标DataFrame(df2)
需要转换为具有二级列头的结构,定义及输出如下:
data2 = [['a', 'b', 'c', 1, 2, 3, 1, 0, 0, 0, 1, 0]] columns2 = [['c0', 'c1', 'c2', 'c0', 'c1', 'c2', 'c0', 'c1', 'c2', 'c0', 'c1', 'c2'], ['i0', 'i0', 'i0', 'i1', 'i1', 'i1', 'i2', 'i2', 'i2', 'i3', 'i3', 'i3']] df2 = pd.DataFrame(data2, columns=columns2) print(df2)
输出结果:
c0 c1 c2 c0 c1 c2 c0 c1 c2 c0 c1 c2 i0 i0 i0 i1 i1 i1 i2 i2 i2 i3 i3 i3 0 a b c 1 2 3 1 0 0 0 1 0
实现代码
可以通过stack()、索引交换和转置快速完成转换:
# 基于原始df1进行转换 s = df1.stack() # 交换多级索引的层级,让原列名作为第一级,原行索引作为第二级 s.index = s.index.swaplevel() # 将Series转为DataFrame并转置,得到目标结构 df2 = s.to_frame().T
执行上述代码后,df2的结构和输出将与目标完全一致。
内容的提问来源于stack exchange,提问作者pyaj
相关产品推荐
相关产品推荐

