使用 pandas.DataFrame.to_html 时如何设置列宽?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52580111/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:03:39  来源:igfitidea点击:

How do I set the column width when using pandas.DataFrame.to_html?

pythonpandas

提问by Xonnel Haon

I have read this, but I am still confused about how I set the column width when using pandas.DataFrame.to_html.

我已经阅读了这篇文章,但我仍然对使用pandas.DataFrame.to_html.

import datetime
import pandas

data = {'Los Angles': {datetime.date(2018, 9, 24): 20.5, datetime.date(2018, 9, 25): 1517.1},
        'London': {datetime.date(2018, 9, 24): 0, datetime.date(2018, 9, 25): 1767.4},
        'Kansas City': {datetime.date(2018, 9, 24): 10, datetime.date(2018, 9, 25): 1.4}}

df = pandas.DataFrame(data=data)

html = df.to_html()

The above code results in : df.to_html result

上面的代码导致: df.to_html 结果

How do I go about forcing the column width so that they are the same?

我如何强制列宽使它们相同?

回答by Irfanuddin

Try this:

尝试这个:

import datetime
import pandas

data = {'Los Angles': {datetime.date(2018, 9, 24): 20.5, datetime.date(2018, 9, 25): 1517.1},
        'London': {datetime.date(2018, 9, 24): 0, datetime.date(2018, 9, 25): 1767.4},
        'Kansas City': {datetime.date(2018, 9, 24): 10, datetime.date(2018, 9, 25): 1.4}}

df = pandas.DataFrame(data=data)
pandas.set_option('display.max_colwidth', 40)

html = df.to_html()

回答by bender

I find it better to use the set_table_attributes function. You are then able to set e.g. a CSS-class to the table. In case you have many tables on your output it is much better readable.

我发现最好使用 set_table_attributes 函数。然后您就可以为表格设置例如一个 CSS 类。如果您的输出中有很多表,它的可读性会更好。

import datetime
import pandas

data = {'Los Angles': {datetime.date(2018, 9, 24): 20.5, datetime.date(2018, 9, 25): 1517.1},
        'London': {datetime.date(2018, 9, 24): 0, datetime.date(2018, 9, 25): 1767.4},
        'Kansas City': {datetime.date(2018, 9, 24): 10, datetime.date(2018, 9, 25): 1.4}}

df = pandas.DataFrame(data=data)

html = df.set_table_attributes('class="table-style"').to_html()

Your CSS could look something like that:

你的 CSS 可能看起来像这样:

    .table-style {
                  width: 100%;
}

    .table-style td {
                  width: 100px;
}