2016-12-16 79 views
2

我试图使用readtable()将CSV文件读入DataFrame。 CSV文件中存在一个不幸的问题,如果给定行的最后一列是空白的,而不是生成那么多的逗号,它只是结束该行。例如,我可以有:Readtable()具有不同的列数 - Julia

Col1,Col2,Col3,Col4 
item1,item2,,item4 
item5 

请注意第三行中只有一个条目。理想情况下,我希望阅读表用NA,NA和NA填写Col2,Col3和Col4的值;但是,由于缺少逗号,因此缺少空字符串,readtable()只是将其视为与列数不匹配的行。如果我使用上面的示例CSV在Julia中运行readtable(),则会出现错误“Saw 2 Row,2 columns,5 fields,* Line 1 6 columns”。如果我在item5之后添加3个逗号,那么它可以工作。

有没有办法解决这个问题,还是我需要修复CSV文件?

回答

3

如果CSV解析不需要太多的引用逻辑,可以很容易地编写一个特殊用途的解析器来处理丢失列的情况。像这样:

function bespokeread(s) 
    headers = split(strip(readline(s)),',') 
    ncols = length(headers) 
    data = [String[] for i=1:ncols] 
    while !eof(s) 
    newline = split(strip(readline(s)),',') 
    length(newline)<ncols && append!(newline,["" for i=1:ncols-length(newline)]) 
    for i=1:ncols 
     push!(data[i],newline[i]) 
    end 
    end 
    return DataFrame(;OrderedDict(Symbol(headers[i])=>data[i] for i=1:ncols)...) 
end 

然后将文件:

Col1,Col2,Col3,Col4 
item1,item2,,item4 
item5 

还会送:

julia> df = bespokeread(f) 
2×4 DataFrames.DataFrame 
│ Row │ Col1 │ Col2 │ Col3 │ Col4 │ 
├─────┼─────────┼─────────┼──────┼─────────┤ 
│ 1 │ "item1" │ "item2" │ "" │ "item4" │ 
│ 2 │ "item5" │ ""  │ "" │ ""  │ 
0

丹·盖茨的答案是好的,但它的一切转换为字符串。

下面的解决方案,而不是“补”的差距,并写入新文件(在存储高效的方式),然后可以正常导入使用readtable():

function fillAll(iF,oF,d=",") 
    open(iF, "r") do i 
     open(oF, "w") do o # "w" for writing 
      headerRow = strip(readline(i)) 
      headers = split(headerRow,d) 
      nCols = length(headers) 
      write(o, headerRow*"\n") 
      for ln in eachline(i) 
       nFields = length(split(strip(ln),d)) 
       write(o, strip(ln)) 
       [write(o,d) for y in 1:nCols-nFields] # write delimiters to match headers 
       write(o,"\n") 
      end 
     end 
    end 
end 

fillAll("data.csv","data_out.csv",";") 
0

更妙的是:只要使用CSV.jl

julia> f = IOBuffer("Col1,Col2,Col3,Col4\nitem1,item2,,item4\nitem5"); # or the filename 

julia> CSV.read(f) 
2×4 DataFrames.DataFrame 
│ Row │ Col1 │ Col2 │ Col3 │ Col4 │ 
├─────┼─────────┼─────────┼───────┼─────────┤ 
│ 1 │ "item1" │ "item2" │ #NULL │ "item4" │ 
│ 2 │ "item5" │ #NULL │ #NULL │ #NULL │