Home > Software design >  My borders don't collapse in pandas styler
My borders don't collapse in pandas styler

Time:12-29

A function that defines the layout of a dataframe. All is well, except I need my borders to collapse. I have tried everything. I need NO borders in my headers(col headers and index) but need a collapsed small grey border in my cells. Strangely enough I also have white borders in my headers even though I did not define that.

`

def style_df(df_):
    def style_negative(v, props=''):
        return props if v < 0 else None
    
    cell_hover = {
    "selector": "td:hover",
    "props": [("background-color", "#7FB3D5")]
    }
    index_names = {
    "selector": ".index_name",
    "props": "font-style: italic; color: white"
    }
    headers = {
    "selector": "th",
    "props": "background-color: #273746; color: white;font-size: 12px;font-family: sans-serif"
    }
    cells = {
    "selector": "td",
    "props": "background-color: white; font-size: 12px;font-family: sans-serif;border:1px solid #707B7C;border-collapse:collapse"
    }  
    x=df_.style\
        .applymap(style_negative, props='color:red;')\
        .format(formatter='{:,.2f}%',na_rep='-')\
        .set_table_styles([cell_hover,index_names, headers,cells])
    return x          




df_dict={"col1":np.random.random(10),"col2":np.random.random(10)}
df_random=pd.DataFrame(df_dict)
df_random
style_df(df_random)

`

I tried border-collapse:collapse in only td and th or only in table. Nothing works.

CodePudding user response:

This is my view after adjusting for the answer of Sergey. Still white space between cells.

enter image description here

CodePudding user response:

headers = {
"selector": "th",
"props": "background-color: #273746; color: white}
}
cells = {
"selector": "td",
"props": "background-color: white; font-size: 12px;font-family: sans-serif;border:1px solid #707B7C;border-collapse:collapse; border: 0.5px solid"
}  

Output:

enter image description here

p.s. the white border for the header is specified in your header, see this example, how it works:

headers = {
    "selector": "th",
    "props": "background-color: #273746; color: green;font-size: 12px;font-family: sans-serif;border-collapse:collapse;  border: solid"
    }
cells = {
    "selector": "td",
    "props": "background-color: white; font-size: 12px;font-family: sans-serif;border:1px solid #707B7C;border-collapse:collapse; border: 0.5px solid"
    }  

enter image description here

  • Related