简体   繁体   English

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

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

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 结果

How do I go about forcing the column width so that they are the same?如何强制列宽使它们相同?

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()

I find it better to use the set_table_attributes function.我发现使用 set_table_attributes 函数更好。 You are then able to set eg a CSS-class to the table.然后,您可以为表格设置一个 CSS 类。 In case you have many tables on your output it is much better readable.如果您的输出中有很多表,则它的可读性会更好。

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;
}

You can now set the col_space argument of to_html .您现在可以设置 to_html 的col_space参数。 col_space specifies the min width of all the columns. col_space 指定所有列的最小宽度。

df.to_html(col_space='75px')

另一种选择是

df.style.set_table_styles([dict(selector='th', props='min-width: 60px;'),])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM