Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

I have read this, but I am still confused about how I set the column width when using 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

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

like image 777
Xonnel Haon Avatar asked Sep 30 '18 16:09

Xonnel Haon


People also ask

How do I change the column width in pandas?

To prevent this, you can use the pd. set_option method to set the column width. After doing this, all the text is displayed again.

How do you create a DataFrame of a certain size?

One way to make a pandas dataframe of the size you wish is to provide index and column values on the creation of the dataframe. This creates a dataframe full of nan's where all columns are of data type object. Save this answer.

How do you set columns in a data frame?

To set column names of DataFrame in Pandas, use pandas. DataFrame. columns attribute. Assign required column names as a list to this attribute.


2 Answers

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()
like image 137
Irfanuddin Avatar answered Sep 28 '22 03:09

Irfanuddin


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;
}
like image 31
bender Avatar answered Sep 28 '22 02:09

bender