2023-04-24

Remove blank line when displaying MultiIndex Python dataframe

I have a MultiIndex Python Dataframe displaying like this:

enter image description here

What can I do to pull up the index names ("index1", "index2") and delete the empty row above the dataframe values to get a view like this? The goal is to export the dataframe in png.

enter image description here

Here is the code that generates the first dataframe:

import pandas as pd
import numpy as np

style_valeurs = {"background-color" : "white", "color" : "black", "border-color" : "black",  "border-style" : "solid", "border-width" : "1px"}

style_col = [{"selector": "thead",
            "props": "background-color:yellow; color :black; border:3px black;border-style: solid; border-width: 1px"
            },{
            'selector':"th:not(.index_name)",
            'props':"background-color: yellow; border-color: black;border-style: solid ;border-width: 1px; text-align:left"
}]

data = np.random.rand(4,4)

columns = pd.MultiIndex.from_product([["A","B"],["C","D"]])

index = pd.MultiIndex.from_product([["x","y"],["1","2"]])

df = pd.DataFrame(data, columns = columns, index = index)

df.rename_axis(["index1","index2"], inplace = True)

df.style.set_properties(**style_valeurs).set_table_styles(style_col)

Thank you for your help!



No comments:

Post a Comment