gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:28:28 26 4
gpt4 key购买 nike

在我的 DataFrame 中,我有一列名为 id在其中,我想让该列可点击,以便表格中的 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)
)

然后在我的 HTML django 模板中将其渲染为 HTML:

{% autoescape off %}
{{ df_products }}
{% endautoescape %}

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

最佳答案

找到它,使用 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

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

df_products = df_products.to_html(index=False, table_id="sellers_table-id", render_links=True,escape=False)

关于python - 如何将标签添加到 pandas dataframe.to_html 链接,以便 url 的绝对路径不会显示在 html 中,而是显示在标签中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57941130/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com