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

如何将Dijkstra路径对应Pandas行存入新DataFrame并导出CSV?

问题分析与解决方案

核心错误点

  1. DataFrame初始化错误:你写的 df_out = pd.DataFrame 是把pandas的DataFrame类赋值给了变量,而非创建空的DataFrame实例。正确写法应为 df_out = pd.DataFrame()。
  2. 错误使用add方法:add是pandas中用于元素级数值相加的方法,完全不适合用来向DataFrame添加行,属于方法误用。

正确实现方式

推荐两种高效写法,避免循环逐行添加(数据量大时会显著降低性能):

方式1:收集目标行后一次性合并

# 收集路径对应的所有行
selected_rows = []
for node in path:
    row = df_cp.loc[df_cp["punto"] == node]
    selected_rows.append(row)

# 合并为新DataFrame并重置索引
df_out = pd.concat(selected_rows, ignore_index=True)

# 导出CSV
df_out.head(2)
df_out.to_csv('file_out2.csv', index=False)

方式2:直接用布尔索引筛选(更简洁)

如果path中的每个node在df_cp["punto"]里唯一存在,可直接用isin方法一次性筛选,无需循环:

# 筛选punto列属于path的所有行
df_out = df_cp[df_cp["punto"].isin(path)].reset_index(drop=True)

# 导出CSV
df_out.head(2)
df_out.to_csv('file_out2.csv', index=False)

原代码报错原因

当你把df_out赋值为pd.DataFrame(类对象)后,调用df_out.add(row)是在调用类方法而非实例方法,后续调用df_out.head()时,类对象没有实例化DataFrame的head方法逻辑,最终触发'int' object has no attribute 'iloc'这类混乱错误——本质是操作对象错误,应该操作实例而非类本身。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 09:25:03