带有 CSS 样式的 Pandas df.to_html
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33226158/
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
Pandas df.to_html with CSS styling
提问by iNoob
Can anyone please explain why the below outputs no data? The Results.htmlis not produced.
谁能解释为什么下面没有输出数据?在Results.html不产生。
df = pd.read_csv(os.path.join(root,filename), skip_blank_lines=True)
df.dropna(how="all", inplace=True)
data = df.sort(ascending=True)
HTML('''<style>.white_space_df td { white-space: normal; }</style>''')
HTML(data.to_html(os.path.join(root, "Results.html"), index=False, na_rep="NA", classes='white_space_df'))
Update
更新
I was able to work out the issue myself, just encase anyone else comes across this below is the working example.
我能够自己解决这个问题,只要把其他人遇到这个问题,下面就是工作示例。
df = pd.read_csv(os.path.join(root,filename), skip_blank_lines=True)
df.dropna(how="all", inplace=True)
data = df.sort(ascending=True)
style = '''<style>.white_space_df td { word-wrap: break-word; }</style>'''
style + data.to_html(os.path.join(root, "Results.html"), index=False, na_rep="NA", classes='white_space_df')
回答by Andy Hayden
The to_htmlmethod savesthe html file (when passed a bufparameter), that is, it saves the xml to Results.html... and the method returns None.
该to_html方法保存html文件(传入buf参数时),即把xml保存到Results.html...,方法返回None。
data.to_html(os.path.join(root, "Results.html"), index=False, na_rep="NA", classes='white_space_df')
If you don't pass a bufargument (the first one) it returns a string:
如果您不传递buf参数(第一个),它将返回一个字符串:
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"])
In [12]: df.to_html()
Out[12]: '<table border="1" class="dataframe">\n <thead>\n <tr style="text-align: right;">\n <th></th>\n <th>A</th>\n <th>B</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>1</td>\n <td>2</td>\n </tr>\n <tr>\n <th>1</th>\n <td>3</td>\n <td>4</td>\n </tr>\n </tbody>\n</table>'
So you want to pass this string to HTML (rather than None):
所以你想把这个字符串传递给 HTML(而不是 None):
HTML(data.to_html(index=False, na_rep="NA", classes='white_space_df'))

