【问题标题】:Format the index in connection with to_html in a Pandas DataFrame在 Pandas DataFrame 中格式化与 to_html 相关的索引
【发布时间】:2016-08-17 14:35:01
【问题描述】:

我希望可以使用 Pandas DataFrame 中的 to_html() 直接格式化索引(列)并输出到 HTML?

类似:

df = DataFrame([[1, 2]], index=['a'], columns=['A', 'B'])
print(df.to_html(formatters={
    'index': lambda elem: '<a href="example.com/{}">{}</a>'.format(elem, elem)}, escape=False))

这不起作用。我没有得到链接。

我想我需要做一些类似的事情

dfc = df.copy()
dfc.index = ['<a href="example.com/{}">{}</a>'.format(i, i) for i in df.index]
print(dfc.to_html(escape=False))

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您应该使用__index__ 而不是index

    print(df.to_html(formatters={
        '__index__': lambda elem: '<a href="example.com/{}">{}</a>'.format(elem, elem)}, escape=False))
    

    来源:The pull request that introduced that feature

    【讨论】:

      猜你喜欢
      • 2019-03-14
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 2014-03-30
      • 2021-11-22
      相关资源
      最近更新 更多