Stryker
Stryker

Reputation: 6120

How to convert a string to clicable URL in pandas dataframe

I have URL column for each record in pandas DataFrame.

Name             CRMLinks                             NamedLink
Clint Eastwood   HTTP://example.com/link1/100e1e         Clint
Iron Side        HTTP://example.com/link2/202e1e         Iron

I want to convert CRMLinks and NamedLink column to clickable links to get to the URL that is shown in CRMLinks.

Here is what I have

base_url= 'https://example.com/'

df['CRM'] = base_url + df['CRM']

def make_clickable(link):
    # target _blank to open new window
    # extract clickable text to display for your link
    text = link.split('=')[1]
    return f'<a target="_blank" href="{link}">{text}</a>'

# link is the column with hyperlinks

df['CRM'] = df['CRM'].apply(make_clickable)

But I only get this in the df['CRM'] cell.

<a target="_blank" href="HTTP://example.com/link1">100e1e</a>

Thanks

Upvotes: 0

Views: 2478

Answers (2)

Pygirl
Pygirl

Reputation: 13349

I guess you need to use:

df.style.format({'CRM': make_clickable})

This will make those clickable


base_url= 'https://example.com/'

df['CRM'] = base_url + df['NamedLink']

def make_clickable(link):
    print(link)
    # target _blank to open new window
    # extract clickable text to display for your link
    text = link.split('=')[0]
    return f'<a target="_blank" href="{link}">{text}</a>'

# link is the column with hyperlinks
df.style.format({'CRM': make_clickable})

    Name            CRMLinks                         NamedLink  CRM
0   Clint_Eastwood  HTTP://example.com/link1/100e1e  Clint  https://example.com/Clint
1   Iron_Side       HTTP://example.com/link2/202e1e  Iron   https://example.com/Iron

Upvotes: 1

Sowjanya R Bhat
Sowjanya R Bhat

Reputation: 1168

I'm guessing this line is the error. Replace your line :

return f'<a target="_blank" href="{link}">{text}</a>'

TO this n try:

return f'<a target="_blank" href="{link}/{text}">{text}</a>'

Upvotes: 0

Related Questions