英文:
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 "")
)
输出:
英文:
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 :
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论