juliaextractdataframes.jl

Extract value from DataFrame as Float64 value not as Vector


The below is the sample dataframe and I want to extract the value bw of Rat as Float64 not as Vector{Float64}.

df = DataFrame(id=["Mouse","Rat"],
               time=[1,1],
               bw=[25.0,100.45]) 

I get a Vector{Float64} when I use the below code.

df[in.(df.id, Ref(["Rat"])), :bw]

Can yo please tell me how can I get only the value of bw=100.45 from the dataframe. I don't want to use the below code, instead I want to reference id=="Rat" and take it that way to be sure I am getting the correct value from a larger dataset.

df[2, :bw]

Thanks again...!


Solution

  • You can do:

    julia> only(df[in.(df.id, Ref(["Rat"])), :bw])
    100.45
    

    The reason why you are getting a vector back is that you are indexing with a vector. This is consistent with base Julia:

    julia> x = ["a", "b"]
    2-element Vector{String}:
     "a"
     "b"
    
    julia> x[[true, false]]
    1-element Vector{String}:
     "a"
    

    So another option is to index with a scalar:

    julia> df[findfirst(in.(df.id, Ref(["Rat"]))), :bw]
    100.45
    

    here the findfirst returns the index of the first true element of your indexing vector, which is a scalar.