如何重新索引Pandas Dataframe的MultiIndex列?

时间:2016-12-16 10:57:33

标签: python pandas multi-index

我在列上有一个DataFrame MultiIndex(可以说是3级):

MultiIndex(levels=[['BA-10.0', 'BA-2.5', ..., 'p'], ['41B004', '41B005', ..., 'T1M003', 'T1M011'], [25, 26, ..., 276, 277]],
           labels=[[0, 0, 0, ..., 18, 19, 19], [4, 5, 6,..., 14, 12, 13], [24, 33, 47, ..., 114, 107, 113]],
           names=['measurandkey', 'sitekey', 'channelid'])

当我通过第一级并且产生DataFrame的子集时:

def cluster(df):
    for key in df.columns.levels[0]:
        yield df[key]

for subdf in cluster(df):
    print(subdf.columns)

列索引确实已经丢失了第一个级别,但MultiIndex仍然包含对子级别中所有其他键的引用,即使它们在子集中缺失。

MultiIndex(levels=[['41B004', '41B005', '41B006', '41B008', '41B011', '41MEU1', '41N043', '41R001', '41R002', '41R012', '41WOL1', '41WOL2', 'T1M001', 'T1M003', 'T1M011'], [25, 26, 27, 28, 30, 31, 32, 3, ....
           labels=[[4, 5, 6, 7, 9, 10], [24, 33, 47, 61, 83, 98]],
           names=['sitekey', 'channelid'])

如何强制subdf仅使用存在的键更新其MultiIndex列?

1 个答案:

答案 0 :(得分:1)

def cluster(df):
    for key in df.columns.levels[0]:
        d = df[key]
        d.columns = pd.MultiIndex.from_tuples(d.columns.to_series())
        yield d