How to Iterate through dataframe using f-strings?

428 views Asked by At

Iterate through dataframe using f-strings

Imagine you have the following df:

d = {'KvK': [0.21, 0.13, 0.1], 'line amount#2': [0.0, 0.05, .05], 'ExclBTW': [0.5, 0.18, .05]}
df = pd.DataFrame(data=d)
df

    KvK line amount#2   ExclBTW
0   0.21    0.00         0.50
1   0.13    0.05         0.18
2   0.10    0.05         0.05

Now, I want to input each KvK value into an API call.

I've tried the following:

for index, row in df.iterrows():
    details = df(row)
    f"https://api.kvk.nl/api/v2/search/companies?user_key=ldbb&q=f{row['KvK']}"

However this does not work.

Desired output:

    KvK line amount#2   ExclBTW    APIoutput#1
0   0.21    0.00         0.50        0.21APIsampleAPIOutput
1   0.13    0.05         0.18        0.13APIsampleAPIOutput
2   0.10    0.05         0.05        0.10APIsampleAPIOutput

Please help!

2

There are 2 answers

0
Dean Taler On
d = {'KvK': [0.21, 0.13, 0.1], 'line amount#2': [0.0, 0.05, .05], 'ExclBTW': [0.5, 0.18, .05]}
df = pd.DataFrame(data=d)

url = f"https://api.kvk.nl/api/v2/search/companies?user_key=ldbb&q=f"
df['APIoutput'] = url + df['KvK'].astype(str) 
0
Aditya On

You can use apply to format your URL string like this:

df['APIOutput'] = df['KvK'].apply(lambda x: f"https://api.kvk.nl/api/v2/search/companies?user_key=ldbb&q=f{x}")