CSV.read()
函数也可以用于读取分隔文件。与readdlm()
相比,CSV.read()
的优点是对于大文件来说速度更快。例如,要读取以下内容:
julia> file =
"""
23 12 13 22
15 61 17 10
1 0 11 12
"""
代码将会是:
julia> CSV.read(IOBuffer(file),delim=" ",ignorerepeated=true,header=false)
3×4 DataFrames.DataFrame
│ Row │ Column1 │ Column2 │ Column3 │ Column4 │
│ │ Int64 │ Int64 │ Int64 │ Int64 │
├─────┼─────────┼─────────┼─────────┼─────────┤
│ 1 │ 23 │ 12 │ 13 │ 22 │
│ 2 │ 15 │ 61 │ 17 │ 10 │
│ 3 │ 1 │ 0 │ 11 │ 12 │
对于小文件,readdlm()
更快。
julia> using BenchmarkTools
julia> @btime CSV.read(IOBuffer(file),delim=" ",ignorerepeated=true,header=false);
68.197 μs (185 allocations: 14.80 KiB)
julia> @btime readdlm(IOBuffer(file));
2.465 μs (20 allocations: 40.70 KiB)
但对于较大的文件,CSV.read()
更快、更高效。
julia> @btime CSV.read(IOBuffer(file^100000),delim=" ",ignorerepeated=true,header=false);
32.027 ms (230 allocations: 3.26 MiB)
julia> @btime readdlm(IOBuffer(file^100000));
142.187 ms (3600025 allocations: 116.44 MiB)
它可以转换为数组,如下所示:
julia> dffile = CSV.read(IOBuffer(file),delim=" ",ignorerepeated=true,header=false);
julia> convert(Matrix, dffile)
3×4 Array{Int64,2}:
23 12 13 22
15 61 17 10
1 0 11 12
许多其他个性化设置可以用于读取不同类型的文件,并在文档中详细说明。