close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I set the column width when using pandas.DataFrame.to_html in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

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

    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.

  2. set the column width when using pandas.DataFrame.to_html

    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.

Method 1

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

Method 2

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.

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:

    .table-style {
                  width: 100%;
}

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

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read