pandas `to_html()` – 如何只为特定行添加边框

huangapple go评论71阅读模式
英文:

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

问题

我有一个数据框架:

import pandas as pd

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

我想要为整个Total行(包括索引)添加底部和顶部边框。目前我有以下代码:

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

很遗憾,它对索引不起作用,也许有更加优雅的方法来实现这个目标?

英文:

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?

答案1

得分: 0

以下是您要翻译的内容:

这里有一个关于 set_table_styles 的建议:

s = (
      data.style
          .set_table_styles(
              {"Total": [ # 在此处更改值以选择另一个索引/行
                  {"selector": "", # 使边框应用于整行
                   "props": "border-bottom: solid; border-top: solid"}
              ]}, axis=1)
)

或者按照您的方法,您可以与 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 "")
)

输出:

pandas `to_html()` – 如何只为特定行添加边框

英文:

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 :

pandas `to_html()` – 如何只为特定行添加边框

huangapple
  • 本文由 发表于 2023年4月20日 00:32:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76056880.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定