Reputation: 1302
In my DataFrame I have column named id
in it, I want to make this column clickable so that the HTML line in the table will be <td><a href="../../link/to/{id}" target="_blank">{id}</a></td>
, the workaround I made is just replace to unicode that return from the to_html
method:
import pandas as pd
from pandas import Timestamp
dict_df_example = {
'ship_price': {0: 25.0, 1: 25.0},
'name': {0: u'prodct example', 1: u'prodct example 2'},
'when_seen': {0: Timestamp('2019-09-07 02:31:07'),
1: Timestamp('2019-09-07 02:40:46')},
'price': {0: 17.0, 1: 17.0},
'id': {0: 101025072, 1: 101021537}
}
df_products = pd.DataFrame.from_dict(dict_df_example)
list_ids = df_products.id.tolist()
df_products = df_products.to_html(index=False, table_id="table-id", render_links=True)
for id in list_ids:
df_products = df_products.replace(
'<td>{0}</td>'.format(id),
'''<td><a href="../../link/to/{id}" target="_blank">{id}</a></td>'''.format(id=id)
)
and then render this to HTML, in my HTML django template:
{% autoescape off %}
{{ df_products }}
{% endautoescape %}
How can I achieve this functionality of get URL with label in pandas?
Upvotes: 3
Views: 2886
Reputation: 1302
found it , using apply function to create href without td like this :
df_products['id'] = df_products['id'].apply(create_clickable_id)
def create_clickable_id(id):
url_template= '''<a href="../../link/to/{id}" target="_blank">{id}</a>'''.format(id=id)
return url_template
and the most important is to add escape=False
to pandas to_html method
df_products = df_products.to_html(index=False, table_id="sellers_table-id", render_links=True,escape=False)
Upvotes: 8