Julia中从数据框列获取向量

4

我有一个 DataFrame

df = DataFrame(x = 1:3, y = 4:6)

3×2 DataFrame
 Row │ x      y     
     │ Int64  Int64 
─────┼──────────────
   11      4
   22      5
   33      6

我该如何将一个列提取为 Vector

我知道可以使用 df[:,:x]df.x 来实现,但是否有一种使用函数的方法来实现?我问这个问题是因为我正在使用 Chain.jl 包,并且想要做出类似以下操作的效果

@chain df begin
    some_manipulations_here
    pull(:x)
end
2个回答

4
您可以执行以下任一操作:
julia> df = DataFrame(x = 1:3, y = 4:6)
3×2 DataFrame
 Row │ x      y
     │ Int64  Int64
─────┼──────────────
   11      4
   22      5
   33      6

julia> @chain df begin
       _.x
       end
3-element Vector{Int64}:
 1
 2
 3

julia> @chain df begin
       getproperty(:x) # same as above
       end
3-element Vector{Int64}:
 1
 2
 3

julia> @chain df begin
       getindex(!, :x) # also _[!, :x]
       end
3-element Vector{Int64}:
 1
 2
 3

julia> @chain df begin
       getindex(:, :x) # also _[:, :x]
       end
3-element Vector{Int64}:
 1
 2
 3

实际上,第一个选项(即使用_.x)在实践中是最简单的。

我展示了其他选项,以突出显示所有特殊语法,例如df.xdf[!, :x]实际上都是函数调用,而特殊语法只是一种便利。


我已经添加了一个编辑,附加了更多的解释。 - Bogumił Kamiński

2

好的,那么一个解决方案是

@chain df begin
    some_manipulations_here
    _ |> df -> df.x
end

但我真的希望有人能提出一个更干净的解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接