iNoob
iNoob

Reputation: 1395

Pandas df.to_html with CSS styling

Can anyone please explain why the below outputs no data? The Results.html is not produced.

df = pd.read_csv(os.path.join(root,filename), skip_blank_lines=True)
df.dropna(how="all", inplace=True)
data = df.sort(ascending=True)
HTML('''<style>.white_space_df td { white-space: normal; }</style>''')
HTML(data.to_html(os.path.join(root, "Results.html"), index=False, na_rep="NA", classes='white_space_df'))

Update

I was able to work out the issue myself, just encase anyone else comes across this below is the working example.

df = pd.read_csv(os.path.join(root,filename), skip_blank_lines=True)
df.dropna(how="all", inplace=True)
data = df.sort(ascending=True)
style = '''<style>.white_space_df td { word-wrap: break-word; }</style>'''
style + data.to_html(os.path.join(root, "Results.html"), index=False, na_rep="NA", classes='white_space_df') 

Upvotes: 1

Views: 9833

Answers (1)

Andy Hayden
Andy Hayden

Reputation: 375475

The to_html method saves the html file (when passed a buf parameter), that is, it saves the xml to Results.html... and the method returns None.

data.to_html(os.path.join(root, "Results.html"), index=False, na_rep="NA", classes='white_space_df')

If you don't pass a buf argument (the first one) it returns a string:

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"])

In [12]: df.to_html()
Out[12]: '<table border="1" class="dataframe">\n  <thead>\n    <tr style="text-align: right;">\n      <th></th>\n      <th>A</th>\n      <th>B</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>3</td>\n      <td>4</td>\n    </tr>\n  </tbody>\n</table>'

So you want to pass this string to HTML (rather than None):

HTML(data.to_html(index=False, na_rep="NA", classes='white_space_df'))

Upvotes: 2

Related Questions