How to add quotes to the start and end of a link in Python?

Question:

I have a dataframe with links and I want to add quotes to the end and start of the quotes. This is how my df looks like:

links
https://us.search.yahoo.com
https://us.search.google.com
https://us.search.wikipedia.com

I want my output to be:

links
'https://us.search.yahoo.com'
'https://us.search.google.com'
'https://us.search.wikipedia.com'

Thank you in advance!

Asked By: CPDatascience

||

Answers:

This is relatively crude but given you’ve not supplied an example it’s the best I can come up with;

import pandas as pd

df = pd.DataFrame({'link': 'https://us.search.yahoo.com', 'text': 'Yahoo', 'title': 'Yahoo Search - Web Search'}, index=[0])
print(df["link"].apply(repr))

Output:

'https://us.search.yahoo.com'
Answered By: Madison Courto

I was curious about the impact of using the inefficient apply method here~

Given:

                          link   text                      title
0  https://us.search.yahoo.com  Yahoo  Yahoo Search - Web Search

I explode its size to 1 million rows:

df = pd.concat([df]*int(1e6), ignore_index=True)

And then run some timing tests:

%timeit df.link.apply(repr)
93.5 ms ± 2.35 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit "'" + df.link + "'"
68.3 ms ± 1.6 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

It’s clear that the vectorized version of this, "'" + df.link + "'" is significantly faster, but it’s unlikely to make a practical difference unless your dataframe is insanely large.

Answered By: BeRT2me
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.