【问题标题】:How to add vectors to the columns of some array in Julia?如何将向量添加到 Julia 中某个数组的列中?
【发布时间】:2014-05-23 22:36:49
【问题描述】:

我知道,使用包DataFrames,只需这样做就可以了

julia> df = DataFrame();

julia> for i in 1:3
          df[i] = [i, i+1, i*2]
       end

julia> df
3x3 DataFrame
|-------|----|----|----|
| Row # | x1 | x2 | x3 |
| 1     | 1  | 2  | 3  |
| 2     | 2  | 3  | 4  |
| 3     | 2  | 4  | 6  |

...但是有什么方法可以在空的Array{Int64,2} 上做同样的事情吗?

【问题讨论】:

    标签: dataframe julia


    【解决方案1】:

    如果您知道最终数组中有多少行,您可以使用hcat

    # The number of lines of your final array
    numrows = 3
    
    # Create an empty array of the same type that you want, with 3 rows and 0 columns:
    a = Array(Int, numrows, 0)
    
    # Concatenate 3x1 arrays in your empty array:
    for i in 1:numrows
        b = [i, i+1, i*2] # Create the array you want to concatenate with a
        a = hcat(a, b)
    end
    

    注意,在这里您知道数组b 具有Int 类型的元素。因此我们可以创建具有相同类型元素的数组a

    【讨论】:

      【解决方案2】:

      遍历矩阵的行:

      A = zeros(3,3)
      for i = 1:3
        A[i,:] = [i, i+1, 2i]
      end
      

      【讨论】:

      • 您的代码看起来不错,但我该如何添加第 4 列呢?我的意思是,如果我不知道我需要多少列,我应该如何实现呢?谢谢
      • Hrm...如果这是一个一维数组,您可以推送!和流行!但这些宏似乎不适用于二维数组。
      • 在 Julia 中,您不能将行附加到具有多个维度的数组。解决方案是将行存储为向量,然后使用vcathcat 创建矩阵。
      • 这种使用hcat 的想法几乎完美!我只是不知道处理初始情况的更好方法,除非已经从向量开始..
      【解决方案3】:

      如果可能,最好从一开始就创建具有所需列数的数组。这样,您只需填写这些列值。使用像hcat() 这样的过程的解决方案效率低下,因为它们每次都需要重新创建数组。

      如果您确实需要将列添加到已经存在的数组中,最好一次性添加所有列,而不是使用hcat() 循环添加。例如。如果你开始:

      n = 10; m = 5;
      A = rand(n,m);
      

      然后

      A = [A rand(n, 3)]
      

      将比:

      for idx = 1:3
          A = hcat(A, rand(n))
      end
      

      例如比较这两者在速度和内存分配上的差异:

      n = 10^5; m = 10;
      A = rand(n,m);
      n_newcol = 10;
      
      function t1(A::Array, n_newcol)
          n = size(A,1)
          for idx = 1:n_newcol
              A = hcat(A, zeros(n))
          end
          return A
      end
      
      function t2(A::Array, n_newcol)
          n = size(A,1)
          [A zeros(n, n_newcol)]
      end
      
      # Stats after running each function once to compile
      @time r1 = t1(A, n_newcol);  ## 0.145138 seconds (124 allocations: 125.888 MB, 70.58% gc time)
      @time r2 = t2(A, n_newcol);  ## 0.011566 seconds (9 allocations: 22.889 MB, 39.08% gc time)
      

      【讨论】:

        猜你喜欢
        • 2019-02-19
        • 1970-01-01
        • 1970-01-01
        • 2017-06-08
        • 1970-01-01
        • 2016-10-26
        • 1970-01-01
        • 2021-04-17
        • 2022-01-06
        相关资源
        最近更新 更多