如何将标签添加到 Pandas dataframe.to_html 链接,以便 url 的绝对路径不会显示在 html 中,而是一个标签?

Ome*_*eld 2 python django pandas

在我的 DataFrameid中,我在其中命名了列,我想让该列可单击,以便表格中的 HTML 行变为<td><a href="../../link/to/{id}" target="_blank">{id}</a></td>,我所做的解决方法只是替换为从该to_html方法返回的 unicode :

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)
    )
Run Code Online (Sandbox Code Playgroud)

然后在我的 HTML django 模板中将其呈现为 HTML:

{% autoescape off %}
    {{ df_products }}
{% endautoescape %}
Run Code Online (Sandbox Code Playgroud)

如何在 Pandas 中实现带有标签的获取 URL 的功能?

Ome*_*eld 5

找到了,使用 apply 函数创建没有 td 的 href ,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

最重要的是escape=False在pandas中添加to_html方法

df_products = df_products.to_html(index=False, table_id="sellers_table-id", render_links=True,escape=False)
Run Code Online (Sandbox Code Playgroud)