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

使用CSV.jl写入CSV文件触发StackOverflowError的解决咨询

CSV.jl中CSV.write()报StackOverflowError的解决方法

问题情况

使用CSV.jl的CSV.write()方法时返回错误:ERROR: LoadError: StackOverflowError:,且提示“--- the last 2 lines are repeated 39990 more times ---”。待写入的DataFrame为129×6维度且无空字段,怀疑函数计数超出数据框行数,出错代码示例如下:

using CSV,DataFrames
file=DataFrame(
        a=1:50,
        b=1:50,
        c=Vector{Any}(missing,50),
        d=Vector{Any}(missing,50))
CSV.write("a.csv",file)
file=CSV.read("a.csv",DataFrame)
c,d=[],[]
for i in 1:nrow(file)
    push!(c,file.a[i]*file.b[i])
    push!(d,file.a[i]*file.b[i]/file.a[i])
end
file[!,:c]=c
file[!,:d]=d
# I found no straight forward way to fill empty columns based on the values of filled columns in a for loop that wouldn't generate error messages
CSV.write("a.csv",DataFrame) # Error in question here

问题根源与解决方法

错误原因

报错的核心问题是最后一行代码写错了:你调用CSV.write("a.csv", DataFrame)时,没有传入要写入的目标DataFrame对象(也就是你之前修改好的file),而是直接调用DataFrame()构造函数。这种情况下CSV.jl内部触发了循环逻辑,最终导致栈溢出错误。

修正代码

只需要把出错的那一行改成传入处理好的file对象即可:

CSV.write("a.csv", file)

额外优化建议

你填充c、d列的循环写法可以简化为更高效的向量化操作,不需要手动遍历行:

# 直接用向量运算替代循环
file[!, :c] = file.a .* file.b
file[!, :d] = file.b  # 等价于原逻辑file.a[i]*file.b[i]/file.a[i],前提是file.a中无0值

这种写法更符合Julia的编程风格,执行效率也更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 03:30:54