【问题标题】:Is there an equivalent (or close) to numpy.loadtxt for julia?julia 的 numpy.loadtxt 是否有等效(或接近)?
【发布时间】:2014-11-07 21:12:01
【问题描述】:

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

除了逐行或逐个字符地迭代之外,还有什么更好的方法可以从文件输入并在 julia 中加载矩阵?

例如,一个文本文件看起来像

5 9
10 3

所以我的矩阵将是

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

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

我这周刚开始接触 julia,所以我仍在尽我所能梳理图书馆和 MIT 的资源。到目前为止,我最好的想法(假设没有与 numpy.loadtxt 等效)是逐行加载到数组中,然后再对其进行整形,但我想让它尽可能高效,这看起来很慢而不是干净的导入方式。

【问题讨论】:

    标签: python numpy io julia


    【解决方案1】:

    试试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
    

    【讨论】:

      【解决方案2】:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-12
        • 1970-01-01
        • 2018-05-24
        • 2015-07-21
        • 2017-08-23
        • 1970-01-01
        • 2021-01-08
        • 1970-01-01
        相关资源
        最近更新 更多