Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas: Use regex to replace strings with hyperlink

Beginner's question.

I'm scraping housing ads with BS4 and analyse the subsequent data with Pandas.

I have a DataFrame with several columns. This issue considers only one of the columns, which looks like,

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

I have a list of links related to the districts. For e.g. district A, the link looks like www.site.com/city/district-A/.

I want to replace each district name in the column (e.g. "A") with <a href="www.site.com/city/district-A/">A</a>. Preferably I do this replacement using regular expressions, since I have a large variety of district names and district links.

To make it more difficult, the district names are non-ASCII, while the links are ASCII.

How do I go about?

like image 587
LucSpan Avatar asked Jul 25 '26 13:07

LucSpan


1 Answers

It seem you need 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>
like image 141
jezrael Avatar answered Jul 27 '26 05:07

jezrael