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 :
How do I go about forcing the column width so that they are the same?
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.
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.
To set column names of DataFrame in Pandas, use pandas. DataFrame. columns attribute. Assign required column names as a list to this attribute.
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. 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With