Writing a multi-index dataframe to Excel file

前端 未结 2 1015
别那么骄傲
别那么骄傲 2021-01-15 20:00

The DataFrame MultiIndex is kicking my butt. After struggling for quite a while, I was able to create a MutliIndex DataFrame with this code

columns = pd.Mult         


        
2条回答
  •  被撕碎了的回忆
    2021-01-15 20:26

    This is a great use for itertools.product. Try this instead in your multiindex creation:

    from itertools import product
    cols = product(
        ['All Properties', '3 Bedroom', '2 Bedroom', '1 Bedroom'],
        ['Avg List Price', 'Median List Price']
    )
    columns = pd.MultiIndex.from_tuples(list(cols))
    ind = pd.Index(['11111'], name='zip')
    vals = ['Val1', 'Val2', 'Val3', 'Val4', 'Val5', 'Val6', 'Val7', 'Val8']
    df = pd.DataFrame(
        vals, index=ind, columns=columns
    )
    

    The issue is: you included zip (which names your index) in the construction of your MultiIndex for your columns (tragically, nothing called MultiColumns exists to clear up that confusion). You need to create your Index (which is a single-level normal pandas.Index) and your columns (which are a two-level pandas.MultiIndex) separately, as above, and you should get expected behavior when you write to excel.

提交回复
热议问题