Apply CSS class to Pandas DataFrame using to_html

前端 未结 4 592
执笔经年
执笔经年 2020-11-28 21:46

I\'m having trouble applying \"classes\" argument with Pandas \"to_html\" method to style a DataFrame.

\"classes : str or list or tuple, default None CSS class(es) t

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 22:16

    I found the most precise, and frankly the easiest way of doing it is skipping the styling, to_html() etc. and converting the DF to a dictionary using the df.to_dict() method.

    Specifically what gave me trouble, was displaying the styled pandas html in an outlook email, as it just wouldn't render properly with the css mess that pandas was producing.

    iterate over the dict and generate the html there by simply wrapping keys/values in the tags that you need, adding classes etc. and concatenate this all into one string. Then paste this str into a prepared template with a predefined css.

    For convenience I found it's useful to export the same df twice, using .to_dict() and to_dict('index') to first fill in the columns and then work your way down row by row. Alternatively just have a list of relevant column names.

    dict_data = [df.to_dict(), df.to_dict('index')]
    
    return_str = ''
    
    for key in dict_data[0].keys():
        return_str = return_str + ''
    
    return_str = return_str + ''
    
    for key in dict_data[1].keys():
        return_str = return_str + ''
        for subkey in dict_data[1][key]:
            return_str = return_str + ''
    
    return_str = return_str + '
    ' + key + '
    ' + key + '' + dict_data[1][key][subkey] + '
    '

    and then return_str goes into the template.

提交回复
热议问题