2017-03-06 7 views
3

私はHTMLとして、このデータフレームを出力しようとしている、と以前`style`をDataFrameの` to_html`クラスと組み合わせて使う方法は?

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

ようto_htmlを使用してしかし、その後、私はStyle機能に出くわし、そのことを考えた

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 

のようなデータフレームを持っています私のDataFrameで浮動小数点数のためのスタイラーを持っているといいですね。同様に、私は

df_styler = df.Style.applymap(colorize) 

しかし、今df_stylerと私のDATAFRAMEに適用することができます

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

Stylerオブジェクトであり、そしてそれはrenderメソッドを持っているのに、私は私がclassesを渡すことができますどのように表示されませんto_htmlと一緒に使用していたリストや浮動フォーマッタ...

Style関数とCSSクラス/フォーマッタを使用して結合できる方法はありますか??

+0

です([その] http://stackoverflow.com/questions/38849992/how-do-i-change-color HTML-table-generated-from-pd-datafr)に基づいていますか? – MaxU

+0

@MaxUはい、しかし、私は 'to_html'に渡した' classes'を使って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

@エリハンセン、あなたは大歓迎です – MaxU

関連する問題