2016-10-07 10 views
2

pandas DataFrameを.htmlに出力してスタイルを適用したい。ドキュメント*は、負の値を赤で表示するこの例を示しています。pandasでhtmlにDataFrameを書き込むときにスタイルマップを適用

import pandas as pd 
import numpy as np 

np.random.seed(24) 
df = pd.DataFrame({'A': np.linspace(1, 10, 10)}) 
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], 
       axis=1) 
df.iloc[0, 2] = np.nan 

def color_negative_red(val): 
    """ 
    Takes a scalar and returns a string with 
    the css property `'color: red'` for negative 
    strings, black otherwise. 
    """ 
    color = 'red' if val < 0 else 'black' 
    return 'color: %s' % color 

s = df.style.applymap(color_negative_red) 
s 

"to_html"メソッドを使用してフォーマットされたdfを出力できますか?そのドキュメントから**私は "フォーマッタ"オプションがあることがわかりますが、私はこの場合にどのように適用するのか分かりません。ここで

私はフォーマットされていないDFを書いている方法です:

df.to_html(r'c:\temp\html.html') 

* http://pandas.pydata.org/pandas-docs/stable/style.html

** http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html

答えて

3

それが最善の(または慣用)であれば、私にはわからない方法それを行うには、それが動作するはずです:

with open('html.html', 'w') as html: 
    html.write(s.render()) 
+0

X、ありがとう! to_htmlのデフォルト値と同じ形式にしておきたいので、関数を直接適用できるのは本当にいいですね。 – sparrow

関連する問題