dataframe - 我想在 Julia 中串联匿名调用

标签 dataframe julia anonymous-function

所以,我正在更多地了解 Julia,并且我想做以下事情:

我有一个 3 行 x 2 列的矩阵,它是固定的, A = 兰特(2,3)

julia> A = rand(2,3)
2×3 Matrix{Float64}:
 0.705942  0.553562  0.731246
 0.205833  0.106978  0.131893

然后,我想要一个匿名函数,它执行以下操作:

a = ones(1,3);
a[2] = rand();

最后我想广播一下 广播(+, Ones(1,3) => a[2]=rand(), A)

所以我有中间一列A,即A[:,2],由两个不同随机数相加,并且在其余的列中,我们添加了一些。

编辑: 如果我添加 a,如下所示:

julia> a = ones(1,3)
1×3 Matrix{Float64}:
 1.0  1.0  1.0

julia> a[2] = rand()
0.664824196431979

julia> a
1×3 Matrix{Float64}:
 1.0  0.664824  1.0

我希望这个a是动态的,并且是一个函数。

这样:

broadcast(+, a, A)

会给出:

julia> broadcast(+, a, A)
2×3 Matrix{Float64}:
 1.70594  0.553562 + rand()  (correct)          1.73125
 1.20583  0.106970 + rand()  (different rand()) 1.13189

而不是:

julia> broadcast(+, a, A)
2×3 Matrix{Float64}:
 1.70594  1.21839  (0.553562 + -> 0.664824)   1.73125
 1.20583  0.771802 (0.106978 + -> 0.664824)   1.13189 

所以,我想到了这个伪代码:

broadcast(+, a=ones(1,3) => a[2]=rand(), A)

形式化:

broadcast(+, <anonymous-fucntion>, A)

第二次编辑:

规则/限制:

  • 规则 1:调用必须是数据透明的。也就是说,A 不得更改状态,就像我们调用 f.(A) 时一样。
  • 规则 2:不创建辅助变量(a 不得存在)。在调用之前和之后必须存在的唯一向量是 A
  • 规则 3:f.(A) 必须是匿名的;也就是说,您不能使用 Define f as function f(A) ... end

最佳答案

需要注意的是,我不知道通过设置这样的人为规则你到底能学到多少东西,一些更简洁的方法是:

julia> A = [ 0.705942  0.553562  0.731246
             0.205833  0.106978  0.131893 ];  # as given

julia> r = 0.664824196431979;  # the one random number

julia> (A' .+ (1, r, 1))'  # no extra vector
2×3 adjoint(::Matrix{Float64}) with eltype Float64:
 1.70594  1.21839   1.73125
 1.20583  0.771802  1.13189

julia> mapslices(row -> row .+ (1, r, 1), A; dims=2)  # one line, but slow
2×3 Matrix{Float64}:
 1.70594  1.21839   1.73125
 1.20583  0.771802  1.13189

julia> B = A .+ 1; @views B[:, 2] .+= (-1 + r); B  # fast, no extra allocations
2×3 Matrix{Float64}:
 1.70594  1.21839   1.73125
 1.20583  0.771802  1.13189

我无法从你的问题中判断你是想要一个随机数还是两个不同的随机数。如果你想要两个,那么你可以这样做:

julia> using Random

julia> Random.seed!(1); mapslices(row -> row .+ (1, rand(), 1), A; dims=2)
2×3 Matrix{Float64}:
 1.70594  0.675436  1.73125
 1.20583  0.771383  1.13189

julia> Random.seed!(1); B = A .+ 1; @views B[:, 2] .+= (-1 .+ rand.()); B 
2×3 Matrix{Float64}:
 1.70594  0.675436  1.73125
 1.20583  0.771383  1.13189

请注意,(-1 .+ rand.()) 并没有在右侧创建一个新数组,它被 .+= 融合到一个循环中B 列。另请注意,B[:,2] .= stuff 仅写入 B,但 B[:, 2] .+= stuff 表示 B[:, 2] .= B[:, 2] .+ stuff 因此,如果没有 @views,右侧的切片 B[:, 2] 将分配一个副本。

关于dataframe - 我想在 Julia 中串联匿名调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69227334/

相关文章:

julia - 为什么 Julia 中的 `where` 语法对换行敏感?

julia - Julia 中可变结构的构造函数中的字典

scala - 将高阶函数转换为匿名函数的正确 Scala 语法?

javascript - 我可以从元素内部获取元素的索引吗?大批

python-2.7 - Python 数据帧在微秒内重新采样

python - Pandas :如何读取分行的文件

julia - julia中有非线性混合整数求解器吗?

如果另一个数据帧值小于 0,则替换 R 数据帧中的值

r - 如何在 R 中使用矢量化根据条件更改 DF 值?

PHP 5 中的 PHP 匿名函数