首页 > 解决方案 > 来自 Julia 中数据框列的向量

问题描述

我有一个DataFrame

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

3×2 DataFrame
 Row │ x      y     
     │ Int64  Int64 
─────┼──────────────
   1 │     1      4
   2 │     2      5
   3 │     3      6

如何将其中一列提取为Vector

我知道我可以做df[:,:x]or df.x,但是有没有办法用函数来做呢?我问的原因是我使用这个Chain.jl包并且想做类似的事情

@chain df begin
    some_manipulations_here
    pull(:x)
end

标签: juliadataframes.jl

解决方案


您可以执行以下操作之一:

julia> df = DataFrame(x = 1:3, y = 4:6)
3×2 DataFrame
 Row │ x      y
     │ Int64  Int64
─────┼──────────────
   1 │     1      4
   2 │     2      5
   3 │     3      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.xordf[!, :x]实际上是函数调用,特殊语法只是为了方便。


推荐阅读