python Pandas : Use regex to replace strings with hyperlink

标签 python regex pandas replace hyperlink

初学者的问题。

我正在使用 BS4 抓取房屋广告并使用 Pandas 分析后续数据。

我有一个包含多个列的 DataFrame。这个问题只考虑其中一列,看起来像,

district | ... |
----------------
   A     | ... |
   B     | ... |
   C     | ... |
  ...    | ... |

我有一个与地区相关的链接列表。例如A区,链接看起来像www.site.com/city/district-A/ .

我想用 <a href="www.site.com/city/district-A/">A</a> 替换列中的每个地区名称(例如“A”) .我最好使用正则表达式进行替换,因为我有各种各样的地区名称和地区链接。

更困难的是,地区名称是非 ASCII 的,而链接是 ASCII 的。

我该怎么办?

最佳答案

看来你需要apply format:

df = pd.DataFrame({'district':['A','B','C']})

df['url'] = df.district.apply('<a href="www.site.com/city/district-{0}/">{0}</a>'.format)
print (df)
  district                                            url
0        A  <a href="www.site.com/city/district-A/">A</a>
1        B  <a href="www.site.com/city/district-B/">B</a>
2        C  <a href="www.site.com/city/district-C/">C</a>

关于 python Pandas : Use regex to replace strings with hyperlink,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42837067/

相关文章:

python - 如何使用 python 和 crontab 安排工作?

python - 系统找不到用ffmpeg指定的文件

python - 将文件读入 Pandas 数据框中,其中行按日期分组

python - 在 python 中使用 .csv 按特定列数据排序

python - Numpy、Pandas 和 Sklearn 中的多维缩放拟合(ValueError)

python - 根据 pandas Dataframe 中的索引从列表中删除元素

c# - 在长字符串中查找所有以@@开头并以@@结尾的单词

java - Mule 3.2 中的分离器

regex - 正则表达式,从一个字符串到另一个字符串

python - 在 python 中按数据框分组并在多列上连接字符串