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

使用DataFrame.at时未插入值反而创建新行的问题排查

问题原因与解决方案

问题根源

  1. 转置后的行索引并非0:执行df.set_index('field').T后,DataFrame的行索引是原DataFrame的列名(转置后成为行标签),而非数字0。此时使用df.at[0, link]会因为索引0不存在,自动新增一行索引为0的记录,这就是每次循环额外创建行的核心原因。
  2. 代码拼写错误:内层循环中requests.get(url_act, headers=headers)里的url_act应为定义好的url_download,该错误会导致请求失败,需优先修正。

修正方案

方案1:重置行索引为0

在转置后添加reset_index(drop=True),强行将行索引设置为0,后续赋值操作就不会新增行:

master_df = pd.DataFrame()
links = [109340678,60375713,...]
ids = [353474,184335,...]
for id in ids:
    url = "https://myurl/{}.json".format(id)
    response = requests.get(url, headers=headers)
    json_obj = json.loads(response.content)
    data = json_obj['data']
    df = pd.DataFrame.from_dict(data)
    df = df.set_index('field').T 
    df = df.reset_index(drop=True)  # 重置行索引为0
    df = df.replace(to_replace='.*patern.*', value=np.NaN, regex=True)
    for link in links:
        url_download= "https://myurl/{id}/{link}".format(id= id, link= link)
        response = requests.get(url_download, headers=headers)  # 修正拼写错误
        df.at[0,link] = response.content
    master_df = master_df.append(df)

方案2:使用现有行索引赋值

不修改行索引,直接获取转置后的行标签进行赋值,从根源避免新增行:

master_df = pd.DataFrame()
links = [109340678,60375713,...]
ids = [353474,184335,...]
for id in ids:
    url = "https://myurl/{}.json".format(id)
    response = requests.get(url, headers=headers)
    json_obj = json.loads(response.content)
    data = json_obj['data']
    df = pd.DataFrame.from_dict(data)
    df = df.set_index('field').T 
    df = df.replace(to_replace='.*patern.*', value=np.NaN, regex=True)
    row_idx = df.index[0]  # 获取转置后的行索引
    for link in links:
        url_download= "https://myurl/{id}/{link}".format(id= id, link= link)
        response = requests.get(url_download, headers=headers)  # 修正拼写错误
        df.at[row_idx, link] = response.content
    master_df = master_df.append(df)

额外优化建议

  • 弃用append改用concat:DataFrame.append已被官方弃用,推荐用列表收集所有子DataFrame,最后一次性合并,效率更高:
dfs = []  # 用列表存储每个循环生成的df
for id in ids:
    # ... 中间逻辑保持不变 ...
    dfs.append(df)
master_df = pd.concat(dfs, ignore_index=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:41:03