csv to html table (pandas) - formatting problem

Viewed 40

I have a simple .csv containing room numbers and the types of equipment in the room. It looks like this:

room1,[computer]
room2,[computer, printer, fax]
room3,[computer, printer, fax, keurig, shredder]
room4,[computer, fax]

I can easily generate an html table using the pd.to_html function, but the equipment list is formatted in such a way that it is all on a single line. I would like it to look like this:

room1   computer
room2   computer
        printer
        fax
room3   computer
        printer
        fax
        keurig
        shredder

I've tried various options in the pd.to_html function but nothing is working. Is there an easy way to apply a word wrap here at the commas?

1 Answers

This might work for you - use a formatter to replace the commas with line breaks in the second column and use escape=False in the .to_html() method:

import pandas as pd
from io import StringIO
from IPython.core.display import display, HTML

with open('test.csv', 'r') as f:
    data = f.read().replace('[', '"').replace(']', '"')

df = pd.read_csv(StringIO(data), header=None)

html_df = df.to_html(index=False, header=False, escape=False,
                    formatters=[None, lambda x: x.replace(', ', '<br>')])

display(HTML(html_df))

Output:

<table border="1" class="dataframe">  <tbody>    <tr>      <td>room1</td>      <td>computer</td>    </tr>    <tr>      <td>room2</td>      <td>computer<br>printer<br>fax</td>    </tr>    <tr>      <td>room3</td>      <td>computer<br>printer<br>fax<br>keurig<br>shredder</td>    </tr>    <tr>      <td>room4</td>      <td>computer<br>fax</td>    </tr>  </tbody></table>

Related