You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何遍历列表调用API查询数据并写入pandas DataFrame计算字段

注意:原有代码调用API时传入的是固定字符串"Shape",需要替换为当前循环的形状名称变量,否则所有请求查询的都是同一个形状的数据。

解决方案

优先推荐批量构建的方案,性能远好于逐行插入:

方案1:先收集全量数据再生成DataFrame(推荐)

pandas逐行修改/插入数据会触发内部数组重建,数据量较大时性能损耗非常明显,建议先把所有查询结果存入普通列表,最后一次性转成DataFrame再批量计算比值列:

import pandas as pd

# 此处替换为你实际的API查询实例
shape_client = YourShapeAPIClient()
# 形状列表
shape_list = ["Rectangle", "Square", "Circle"]
# 临时存储所有行数据
data_rows = []

for shape_name in shape_list:
    # 调用API查询长宽数据
    length = shape_client.length(shape_name)
    width = shape_client.width(shape_name)
    data_rows.append({
        "Shape": shape_name,
        "Length": length,
        "Width": width
    })

# 一次性生成DataFrame
Shapes = pd.DataFrame(data_rows)
# 批量计算比值列
Shapes["Ratio_Length2Width"] = Shapes["Length"] / Shapes["Width"]

# 输出结果
print(Shapes)

方案2:逐行插入到已初始化的DataFrame

如果你需要沿用现有初始化空DataFrame的写法,循环内可以用loc按索引赋值:

import pandas as pd

# 初始化空DataFrame
Shapes = pd.DataFrame({
    'Shape': [],
    'Length': [],
    'Width': [],
    'Ratio_Length2Width':[]
})

# 此处替换为你实际的API查询实例
shape_client = YourShapeAPIClient()
shape_list = ["Rectangle", "Square", "Circle"]

for idx, shape_name in enumerate(shape_list):
    length = shape_client.length(shape_name)
    width = shape_client.width(shape_name)
    ratio = length / width
    # 按行索引赋值
    Shapes.loc[idx] = [shape_name, length, width, ratio]

print(Shapes)

两种方案的输出都符合预期格式。

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:15:01