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

Pandas循环使用append追加行后DataFrame仍仅含单行问题排查

问题根本原因
  • pandas的DataFrame.append()方法不是原地修改操作:调用该方法时不会改动原有DataFrame对象,只会返回一个拼接完成的新DataFrame对象。你的代码没有将返回的新对象赋值回matrixdf,所以matrixdf始终停留在初始化的状态,只会保留第一行数据。
  • 额外说明:pandas 1.4及以上版本已经正式弃用append()方法,后续版本会直接移除该接口,更推荐使用pd.concat()完成DataFrame拼接操作。
修正后代码
import pandas as pd
import time

def distance_count(self):
  m = self.client.distance_matrix(self.origins, self.destinations)
  matrixdf = pd.json_normalize(m,['rows','elements']) 
  print("init print")
  print(matrixdf)
  next_time = time.time()
  for i in range(5):
   matrix = self.client.distance_matrix(self.origins, self.destinations)
   matrixdf2 = pd.json_normalize(matrix,['rows','elements'])
   print("row1")
   print(matrixdf2)
   # 改动点1:将拼接结果赋值回原变量
   # 写法1 兼容旧版本append的写法:
   # matrixdf = matrixdf.append(matrixdf2, ignore_index=True)
   # 写法2 推荐的concat写法,适配新版本pandas:
   matrixdf = pd.concat([matrixdf, matrixdf2], ignore_index=True)
   print("full")
   print(matrixdf)
   wait_seconds = 5
   next_time += wait_seconds
   time.sleep(max(0, next_time - time.time()))
  matrixdf.to_csv('dataset.csv', index=False)
  files.download('dataset.csv')

补充说明:原代码中循环体内修改i = i +5的操作不会生效,for循环遍历range(5)时每次迭代会自动给i赋新值,该写法无实际作用,已替换为直接设置等待间隔的写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:54:04