【问题标题】:Vector from Dataframe Column in Julia来自 Julia 中数据框列的向量
【发布时间】:2021-10-29 09:53:47
【问题描述】:

我有一个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]df.x,但有没有办法用函数来代替?我问的原因是我使用 Chain.jl 包并想做类似的事情

@chain df begin
    some_manipulations_here
    pull(:x)
end

【问题讨论】:

    标签: julia dataframes.jl


    【解决方案1】:

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

    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.xdf[!, :x] 实际上是函数调用,特殊语法只是为了方便。

    【讨论】:

    • 我添加了一个带有附加解释的编辑。
    【解决方案2】:

    好的,所以一个解决方案是

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

    但我实际上希望有人能提出更清洁的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 1970-01-01
      • 1970-01-01
      • 2019-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多