lalatei
lalatei

Reputation: 57

Nested for loop in python to replace strings in url

I have an url that I need to replace 4 parameters in it. The first parameter is already set (value = 3) and the other 3 are based on replacing each parameter by each row of a specific column of a given DataFrame.

I can separately make those replacements for each of the 3 parameters, but the way it's been done will not replace all the parameters at once. What I want to be able to do is replace all of them at once to generate multiple url's.

CODE:

import pandas as pd

url = 'https://parameter1 = replace1, parameter2 = replace2, parameter3 = replace3, parameter4 = replace4'
df = pd.DataFrame({ 'A' : ('foo1', 'foo2', 'foo3'),'B' : (1,2,3), 'C' : ('text1', 'text2', 'text3')})
value = '3'

for i in df['A']:
    new_url = url.replace("replace1", value)
    new_url = new_url.replace("replace2", i)
    print(new_url)

for j in df['B']:
    new_url = url.replace("replace1", value)
    new_url = new_url.replace("replace3", str(j))
    print(new_url)

for k in df['C']:
    new_url = url.replace("replace1", value)
    new_url = new_url.replace("replace3", k)
    print(new_url)

The output that I want would be as followed:

OUTPUT NEEDED:

url = 'https://parameter1 = 3, parameter2 = foo1, parameter3 = 1, parameter4 = text1'
url = 'https://parameter1 = 3, parameter2 = foo2, parameter3 = 2, parameter4 = text2'
url = 'https://parameter1 = 3, parameter2 = foo3, parameter3 = 3, parameter4 = text3'

I would really much appreciate if anyone can help me with this! Thank you.

Upvotes: 0

Views: 403

Answers (1)

Mr. T
Mr. T

Reputation: 12410

Why don't you add a column for url to your dataframe?

import pandas as pd

url = 'https://parameter1 = replace1, parameter2 = replace2, parameter3 = replace3, parameter4 = replace4'
df = pd.DataFrame({ 'A' : ('foo1', 'foo2', 'foo3'),'B' : (1,2,3), 'C' : ('text1', 'text2', 'text3')})
value = '3'

df['value'] = value
df['url'] = 'https://parameter1 = '+ df['value'].astype(str) +', parameter2 = '+ df['A'].astype(str) +', parameter3 = '+ df['B'].astype(str) +', parameter4 = ' + df['C'].astype(str)

print(df)

I assume this is a rather conceptual question, because an url must not contain literal space.

Upvotes: 1

Related Questions