pandas 使用样式器格式化数据框索引和列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45492855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:10:51  来源:igfitidea点击:

Formatting of dataframe index and columns using styler

pythonhtmlcsspandas

提问by Eric B

I am quite new with htmland the pandas dataframe styler, but here is my problem:

我对html和很陌生pandas dataframe styler,但这是我的问题:

I wrote the following code

我写了以下代码

import pandas as pd

df = pd.DataFrame([1000000.0, 1000000.0], index=pd.bdate_range('2017-08-01', '2017-08-02'))

styler = df.style
styler = styler.format("{:,.0f}")
styler = styler.set_properties(**{'width': '100px', 'text-align': 'right'})

Which yield the following

产生以下结果

enter image description here

在此处输入图片说明

I understand how to format the various elements of the dataframeI am working with. However, I would like to format my indexand columntitle. In particular, i would like to format my indexas a date without the time, and I would like to align my columnname to the right, like I did with my values. More specifically, is there an efficient to access the indexand columnsin the pandas styler.

我了解如何格式化dataframe我正在使用的各种元素。但是,我想格式化我的indexcolumn标题。特别是,我想将我的格式设置index为没有时间的日期,并且我想将我的column名字对齐到右边,就像我对我的价值观所做的那样。更具体地,是有一种有效的访问indexcolumnspandas styler

回答by Psidom

You could try something like this, see table styles:

您可以尝试这样的操作,请参阅表格样式

import pandas as pd
?
df = pd.DataFrame([1000000.0, 1000000.0], index=pd.bdate_range('2017-08-01', '2017-08-02'))
?
df.index = df.index.strftime("%Y-%m-%d")
styler = df.style
styler = styler.format("{:,.0f}")
styler = styler.set_properties(**{'width': '100px', 'text-align': 'right'})

styler.set_table_styles(
# select the table header with th and set it right align
    [dict(selector="th", props=[("text-align", "right")])]   
)

enter image description here

在此处输入图片说明