是否有与julia相同(或接近)的numpy.loadtxt?

时间:2014-11-07 21:12:01

标签: python numpy io julia

我正在尝试将我的一些python程序转换为julia,并且要求我从txt文件中获取矩阵形状的值,然后继续使用矩阵进行乘法等。

那么有没有更好的方法从文件输入并在julia中加载矩阵,除了迭代线或字符?

例如,文本文件看起来像

5 9
10 3

所以我的矩阵就是

[[5,9],
 [10,3]]

然后我用它来乘以其他矩阵等。

本周我刚刚开始使用朱莉娅,所以我仍然会尽力梳理图书馆和麻省理工学院的资源。到目前为止,我最好的想法(假设没有相当于numpy.loadtxt)将逐行加载到数组然后只是重新形成它,但我想尽可能高效,这似乎是一个缓慢而不是干净的进口方式。

2 个答案:

答案 0 :(得分:5)

试试Readdlm()。查看此article了解详情

julia> file="23 12 13 22
       15 61 17 10
       1 0 11 12"

您可以将其读取并转换为数组readdlm(IOBuffer(file)),也可以通过这种方式强制数组的项为整数readdlm(IOBuffer(file),int)

julia> readdlm(IOBuffer(file))
3x4 Array{Float64,2}:
 23.0  12.0  13.0  22.0
 15.0  61.0  17.0  10.0
 1.0   0.0   11.0  12.0

答案 1 :(得分:0)

CSV.read()函数还可用于读取定界文件。 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

可以执行许多其他自定义操作来读取不同类型的文件,这些自定义操作在documentation中有详细说明。

相关问题