You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Pandas DataFrame列中的字符串值格式化为指定HTML标签?

Formatting Pandas DataFrame Column into HTML Strings

Got it, let's walk through how to get your desired HTML formatting for the "B" column in your DataFrame. Since you already know how to use map() for numeric formatting (like the currency example you mentioned), we can adapt that same approach here to insert each column value into your HTML template.

Step 1: Create the Sample DataFrame

First, let's set up your example data:

import pandas as pd

df = pd.DataFrame({'A': [1, 2], 'B': ['Hello', 'Hello']})

Step 2: Apply the HTML Formatting

You have two straightforward options to format each value in the "B" column:

Option 1: Using map() with a Format String

This mirrors the currency formatting pattern you saw before. We'll define an HTML template string with a placeholder {} where each column value will be inserted:

# Define the HTML template with a placeholder for the column value
html_template = '<br> <a href="{}" title=Link; style="background-color: orange"> Title </a> </br>'

# Apply the template to each element in column B
df['B'] = df['B'].map(html_template.format)

Option 2: Using a Lambda Function (More Explicit)

If you prefer clearer visibility into how the value is plugged into the template, a lambda function works great:

df['B'] = df['B'].map(lambda x: f'<br> <a href="{x}" title=Link; style="background-color: orange"> Title </a> </br>')

Result

After running either of these, your DataFrame will match exactly what you wanted:

A                                                                 B
0  1  <br> <a href="Hello" title=Link; style="background-color: orange"> Title </a> </br>
1  2  <br> <a href="Hello" title=Link; style="background-color: orange"> Title </a> </br>

Note: If you see escaped quotes (\") when viewing the DataFrame output, that's just Python's way of displaying strings with embedded quotes— the actual HTML will be valid with the correct href value.

内容的提问来源于stack exchange,提问作者alb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 02:49:09