2017-03-06 27 views
3

我有這樣如何將`style`與DataFrame上的`to_html`類一起使用?

df = pd.DataFrame(np.random.randn(10).reshape(2, 5)) 

df 
#    0   1   2   3   4 
# 0 -0.067162 -0.505401 -0.019208 1.123936 0.087682 
# 1 -0.373212 -0.598412 0.185211 0.736143 -0.469111 

一個數據幀我試圖輸出這個數據幀爲HTML,和以前使用to_html

df.to_html(classes=['table', 'table-hover', 'table-bordered'], 
      float_format=lambda x: '{0:.3f}s'.format(x)) 

但後來我遇到了Style特徵來了,並認爲這在我的DataFrame中有一個用於浮動的樣式器會很好。像

def colorize(num) 
    color = 'red' if (np.isnan(num) or num > 0) else 'green' 
    return 'color: %s' % color 

,我可以申請我的數據框與

df_styler = df.Style.applymap(colorize) 

但現在df_stylerStyler對象,儘管它有一個render方法,我不知道怎樣才能通過classes列表或浮動格式化我用to_html了...

有沒有一種方法,我可以結合使用Style函數和CSS類/格式化程序中找到to_html

+0

[是](http://stackoverflow.com/questions/38849992/how-do-i-change-color -based-on-value-of-html-table-generated-from-a-pd-datafr)你想要什麼? – MaxU

+0

@MaxU是的,但我也想使用傳遞給'to_html'的''類來呈現html和float格式化程序;這是我的問題。 –

+0

你可能想檢查[this](http://stackoverflow.com/questions/38511373/change-the-color-of-text-within-a-pandas-dataframe-html-table-python-using-style) – MaxU

回答

2

試試這個:

html = df.style.applymap(colorize) \ 
     .set_table_attributes('border="1" class="dataframe table table-hover table-bordered"') \ 
     .set_precision(3) \ 
     .render() 

with open('d:/temp/a2.html', 'w') as f: 
    f.write(html) 

結果:

enter image description here

+0

'set_table_attributes'我錯過了...謝謝! –

+0

@EricHansen,不客氣 – MaxU

相關問題