Here's a solution that will display your pandas DataFrame in Jupyter Notebook with clickable URLs. This uses HTML formatting to create hyperlinks:
import pandas as pd
from IPython.display import display, HTML
# Assuming your DataFrame is called 'df'
def make_clickable(url, title):
return f'<a target="_blank" href="{url}">{title}</a>'
# Create a new DataFrame with clickable links
df_display = df.copy()
df_display['title'] = df.apply(lambda row: make_clickable(row['url'], row['title']), axis=1)
# Display the DataFrame with clickable links
display(HTML(df_display.to_html(escape=False)))
This code will:
- Create clickable links that open in a new tab (using
target="_blank")
- Show the title as the clickable text
- Display the DataFrame as an HTML table in Jupyter Notebook
Here's a complete example with sample data to demonstrate how it works:
import pandas as pd
from IPython.display import display, HTML
# Sample data
data = {
'title': ['Google', 'Stack Overflow', 'Python Docs'],
'url': ['https://www.google.com', 'https://stackoverflow.com', 'https://docs.python.org']
}
df = pd.DataFrame(data)
# Function to make URLs clickable
def make_clickable(url, title):
return f'<a target="_blank" href="{url}">{title}</a>'
# Create a new DataFrame with clickable links
df_display = df.copy()
df_display['title'] = df.apply(lambda row: make_clickable(row['url'], row['title']), axis=1)
# Display the DataFrame with clickable links
display(HTML(df_display.to_html(escape=False)))
Important notes:
- Make sure you're running this in a Jupyter Notebook environment
- The
escape=False parameter is necessary to render the HTML properly
- The links will open in a new tab due to
target="_blank"
- If you want to style the table further, you can add CSS to the HTML output
If you want to see both the title and the URL (with only the title being clickable), you can modify the code like this:
import pandas as pd
from IPython.display import display, HTML
# Function to make URLs clickable
def make_clickable(url, title):
return f'<a target="_blank" href="{url}">{title}</a>'
# Create a new DataFrame with clickable links
df_display = df.copy()
df_display['title'] = df.apply(lambda row: make_clickable(row['url'], row['title']), axis=1)
# Display the DataFrame with clickable links
display(HTML(df_display[['title', 'url']].to_html(escape=False)))
This will show both columns, but only the title will be clickable.