首页 > 解决方案 > 如何使用 f 字符串遍历数据框?

问题描述

使用 f 字符串遍历数据框

想象一下,您有以下 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

现在,我想将每个 KvK 值输入到 API 调用中。

我尝试了以下方法:

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']}"

但是,这不起作用。

期望的输出:

    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

请帮忙!

标签: pythonpandasnumpyf-stringcfstring

解决方案


您可以使用 apply 来格式化您的 URL 字符串,如下所示:

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

推荐阅读