如何将Pandas DataFrame的单级列索引转换为多级列索引
实现方案
你可以通过pandas.MultiIndex.from_arrays方法实现需求,全程不会修改原始DataFrame的数据:
- 先复制原始DataFrame生成新对象,避免改动原有数据
- 构建两级列索引数组,第一级为上层分组标识(A/B),第二级保留原有列名
- 将新的多级索引赋值给新DataFrame的columns属性
完整示例代码
import pandas as pd # 模拟你的原始DataFrame df = pd.DataFrame( [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]], columns=["A1", "A2", "A3", "B1", "B2", "B3"] ) # 复制原数据,不修改原有内容 new_df = df.copy() # 方式1:自动根据列名首字母生成分组,适合列名规则的场景 new_df.columns = pd.MultiIndex.from_arrays( [ [col[0] for col in df.columns], # 上层索引:A/B df.columns # 下层索引:保留原有列名 ] ) # 方式2:手动指定分组,适合列名不规则、按位置分组的场景(前3列A组,后3列B组) # group_level = ["A"] * 3 + ["B"] * 3 # new_df.columns = pd.MultiIndex.from_arrays([group_level, df.columns]) # 验证结果 print(new_df)
输出结果符合你预期的两级列索引结构,原始df的数据和索引不会有任何改动。
内容的提问来源于stack exchange,提问作者Marioanzas
相关产品推荐
相关产品推荐

