婷婷同学_
在熊猫中,最里面的索引必须标记每一行。因此,必须手动处理最内层的索引,如@David Erickson 的回答所示。Pandas 自动隐藏外部索引;看下面的例子:import pandas as pdtuples = [["2020-07-15", "N-S"], ["2020-07-15", "N-S"], ["2020-07-15", "CSD"], ["2020-07-15", "CSD"], ["2020-07-15", "A"], ["2020-07-15", "B"] ]index = pd.MultiIndex.from_tuples(tuples, names=['Date', 'ConstraintType'])df = pd.DataFrame([ ["w1", 521133], ["w2", 550260], ["d1", 522417], ["d2", 534542], ["d4", 534905], ["d5", 534904],], columns=["Col1", "Col2"], index=index)print(df, '\n'*2)print(df.swaplevel(0,1))退货: Col1 Col2Date ConstraintType 2020-07-15 N-S w1 521133 N-S w2 550260 CSD d1 522417 CSD d2 534542 A d4 534905 B d5 534904 Col1 Col2ConstraintType Date N-S 2020-07-15 w1 521133 2020-07-15 w2 550260CSD 2020-07-15 d1 522417 2020-07-15 d2 534542A 2020-07-15 d4 534905B 2020-07-15 d5 534904重置索引,清理以前的多索引列,然后保存到 Excel,无需设置 merge_cells 选项:df = df.reset_index(drop=False)row_filt = df['ConstraintType'].eq(df['ConstraintType'].shift())df.loc[row_filt, 'ConstraintType'] = ''row_filt = df['Date'].eq(df['Date'].shift())df.loc[row_filt, 'Date'] = ''df.to_excel(r'C:\Users\ram\Desktop\z1.xlsx')生成以下 Excel: