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
Formatting of dataframe index and columns using styler
提问by Eric B
I am quite new with html
and 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
产生以下结果
I understand how to format the various elements of the dataframe
I am working with. However, I would like to format my index
and column
title. In particular, i would like to format my index
as a date without the time, and I would like to align my column
name to the right, like I did with my values. More specifically, is there an efficient to access the index
and columns
in the pandas styler
.
我了解如何格式化dataframe
我正在使用的各种元素。但是,我想格式化我的index
和column
标题。特别是,我想将我的格式设置index
为没有时间的日期,并且我想将我的column
名字对齐到右边,就像我对我的价值观所做的那样。更具体地,是有一种有效的访问index
和columns
在pandas 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")])]
)