【问题标题】:Flask: Make row of Dataframe.to_html() clickable烧瓶:使 Dataframe.to_html() 的行可点击
【发布时间】:2019-12-21 18:19:34
【问题描述】:

我自动生成了显示一些数据的数据框。我想将每一行链接到一个路由'/row_details,其中一些列作为参数发送。

@app.route('/')
def index():
    df = get_df()
    return render_template('table.html',  tables=[df.to_html(classes='data')])

@app.route('/row_details')
def row_details():
    column1 = request.args.get('column1')
    column2 = request.args.get('column2')
    #do something with those columns

我想我可以为包含 URL + GET 参数的数据框生成一个新列,但是有没有更好的方法让整行可点击?

模板的重要部分现在看起来像这样:

{% for table in tables %}
       {{ table|safe }}
{% endfor %}

【问题讨论】:

  • 我认为使用<a></a> 创建列是更好的方法。其他方法需要内部 {% for %}{% if %} 来转换模板中的每个值 - 所以它会更复杂。
  • 在文档to_html 中我找到了选项formatters= - 我从未使用过它,但也许它可以转换列中的值。

标签: python pandas flask jinja2


【解决方案1】:

如果您想单独格式化列 - 不连接两列中的值 - 那么您可以在 to_html() 中使用 formatters

如果要将 HTML 放入列中,还必须使用 escape=False。通常它将< > 转换为> <

顺便说一句:我还必须设置 'display.max_colwidth',因为它会截断列中的文本。

import pandas as pd

df = pd.DataFrame({'url':[
    'https://stackoverflow.com',
    'https://httpbin.org',
    'https://toscrape.com',
]})

pd.set_option('display.max_colwidth', -1)
result = df.to_html(formatters={'url':lambda x:f'<a href="{x}">{x}</a>'}, escape=False)

print(result)

结果:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>url</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td><a href="https://stackoverflow.com">https://stackoverflow.com</a></td>
    </tr>
    <tr>
      <th>1</th>
      <td><a href="https://httpbin.org">https://httpbin.org</a></td>
    </tr>
    <tr>
      <th>2</th>
      <td><a href="https://toscrape.com">https://toscrape.com</a></td>
    </tr>
  </tbody>
</table>

但是,如果您想使用两列中的值创建链接,请在 DataFrame 中创建新列。

最终你必须在模板中格式化所有内容(不使用to_html

df = pd.DataFrame({
    'url':[
        'https://stackoverflow.com',
        'https://httpbin.org',
        'https://toscrape.com',
    ],
    'name':[
        'Ask question',
        'Test requests',
        'Learn scraping'
    ]
})

<table>
{% for row in dt.iterrows() %}
    <tr><td><a href="{{ row['url'] }}">{{ row['name'] }}</a></td></tr>
{% endfor %}
</table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2012-03-29
    • 2020-08-14
    • 2021-05-17
    • 2012-06-16
    • 2018-04-15
    • 1970-01-01
    相关资源
    最近更新 更多