Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing full contents of Pandas dataframe to HTML table

I am embedding links in one column of a Pandas dataframe (table, below) and writing the dataframe to hmtl.

Links in the dataframe table are formatted as shown (indexing first link in table):

In: table.loc[0,'Links']
Out: u'<a href="http://xxx.xx.xxx.xxx/browser/I6.html">I6</a>'

If I view (rather than index a specific row) the dataframe (in notebook), the link text is truncated:

<a href="http://xxx.xx.xxx.xxx/browser/I6.html...  

I write the dataframe to html:

table_1=table.to_html(classes='table',index=False,escape=False)

But, the truncated link (rather than the full text) is written to the html table:

 <td> <a href="http://xxx.xx.xxx.xxx/browser/I6.html...</td>\n

I probably need an additional parameter for to_html().

Look at the documentation now, but advice appreciated:

http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_html.html

Thanks!

like image 695
lmart999 Avatar asked Jul 31 '14 23:07

lmart999


People also ask

How do I export pandas DataFrame to HTML?

DataFrame. to_html() method is used for render a Pandas DataFrame. Return : Return the html format of a dataframe.

How do you plot a whole data frame?

We can plot a dataframe using the plot() method. But we need a dataframe to plot. We can create a dataframe by just passing a dictionary to the DataFrame() method of the pandas library.

How do I read full text in pandas?

We can read data from a text file using read_table() in pandas. This function reads a general delimited file to a DataFrame object. This function is essentially the same as the read_csv() function but with the delimiter = '\t', instead of a comma by default.

How do you convert a DataFrame to a table in Python?

Example 1 : One way to display a dataframe in the form of a table is by using the display() function of IPython. display .


1 Answers

So there is probably a pandas-specific explanation, but you could also work around the problem by (a) replacing the links with a key value, (b) writing the html table string, and then (c) replacing the keys with the appropriate links.

For example, replace each link with a key, storing the keys in a dict:

map = {}
for i in df.index:
    counter = 0
    if df.ix[i]['Links'] in map:
        df.ix[i, 'Links'] = map[df.ix[i]['Links']]
    else:
        map[df.ix[i, 'Links']] = 'href' + str(counter)
        counter += 1
        df.ix[i, 'Links'] = map[df.ix[i]['Links']]

Write the table:

table_1 = df.to_html(classes='table',index=False,escape=False)

Re-write the links:

for key, value in map.iteritems():
    table_1 = table_1.replace(value, key)
like image 166
user1893148 Avatar answered Oct 19 '22 15:10

user1893148