Julia DataFrame删除全零列函数报错:BoundsError索引越界求助
问题排查与修复
你的代码存在三个关键问题,直接导致了BoundsError:
1. 变量拼写错误
代码中定义的列表是emptyColList,但append!操作时误写为empyColList(缺少字母t),这会触发未定义变量错误,不过你遇到的BoundsError主要来自后续逻辑问题。
2. 错误收集列内容而非列标识符
eachcol(df)返回的是列的数值数组,你把这些数值存入emptyColList后传给Not()时,DataFrames无法将数值识别为列索引/列名,因此引发索引越界错误。你需要收集的是列名或列的位置索引,而非列的内容。
3. 全零列判断逻辑不准确
sum(col) == 0无法精准判断全零列——比如列包含1和-1时,总和为0但并非全零。正确的判断应该是检查列中所有元素是否都为0,用all(x -> x == 0, col)。
修正后的代码
方式一:循环收集列名(直观易懂)
function delEmptyCol(df) emptyColList = String[] # 明确类型为字符串数组,存储列名 for (colname, col) in pairs(eachcol(df, true)) # 同时获取列名和列内容 if all(x -> x == 0, col) push!(emptyColList, colname) end end newdf = select!(df, Not(emptyColList)) return newdf end
方式二:简洁向量化写法(推荐)
利用DataFrames的选择器语法,一行完成筛选,避免显式循环:
function delEmptyCol(df) return select!(df, Not([col for col in names(df) if all(x->x==0, df[!,col])])) end
测试验证
先创建正确的测试DataFrame(修正你原测试数据的排版笔误):
using DataFrames df2 = DataFrame(KFC=[1,2,3], Mc=[0,0,0], Piz=[4,5,6])
运行delEmptyCol(df2)后,会得到正确结果(删除全零的Mc列):
3×2 DataFrame Row │ KFC Piz │ Int64 Int64 ─────┼────────────── 1 │ 1 4 2 │ 2 5 3 │ 3 6
注:你原期望结果中写的保留Mc列是笔误,Mc是全零列,应该被删除。
内容的提问来源于stack exchange,提问作者Jason Chen
相关产品推荐
相关产品推荐

