2017-08-03 66 views
1

我與htmlpandas dataframe styler,但在這裏,很新列的格式是我的問題:數據框中指數和使用斯泰勒

我寫了下面的代碼

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'}) 

其產生以下

enter image description here

我知道如何格式化dataframe的各種元素我在一起工作。但是,我想要格式化我的indexcolumn標題。特別是,我想將我的index作爲日期格式,而且我希望將我的column名稱與右側對齊,就像我對我的值所做的一樣。更具體地說,是否有效地訪問pandas styler中的indexcolumns

+1

其中一個造型的侷限性:「你只能在樣式值,而不是索引或列」。 https://pandas.pydata.org/pandas-docs/stable/style.html#Limitations – Alexander

回答

3

你可以嘗試這樣的事情,看到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

+2

你甚至可以在tr上放置一個firstchild僞選擇器來僅確定第一個th ...如果這將是一個問題。 – piRSquared

+1

非常感謝,它真的幫助! –