Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas `to_html()` – how to make only specific rows bordered

I have a dataframe

import pandas as pd

data = pd.DataFrame(index = ["Name1", "Name2", "Total"])
data["A"] = [1,2,3]
data["B"] = [2,1,3]
data

and I want to have bottom and top border for the entire Total row (including index). Currently I have the following:

s = data.style.applymap(lambda x: "border-bottom: solid; border-top: solid", subset = ("Total", slice(None)))

It doesnt work for index unfortunately and maybe there is more elegant way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is a proposition with set_table_styles :

s = (
      data.style
          .set_table_styles(
              {"Total": [ #change the value here to choose another index/row
                  {"selector": "", #so the borders apply to the entire row
                   "props": "border-bottom: solid; border-top: solid"}
              ]}, axis=1)
)

Or following your approach, you can chain it with applymap_index :

s = (
      data.style
          .applymap(lambda e: "border-bottom: solid; border-top: solid",
                        subset = ("Total", slice(None)))
          .applymap_index(lambda idx: "border-bottom: solid; border-top: solid"
                        if idx == "Total" else "")
)

Output :

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading