Seeker
Seeker

Reputation: 31

Julia: create empty DataFrame and then fill part of it with Float64 values

I need to create empty DataFrame and later fill only some cells with Float64 values. If I indicate with "missing" values while creating df, then I get error when I want to insert values. I receive no error if I insert float values right away, but then my df is not empty.

Maybe the question is, how to convert df right away with "missing" values?

End result should be like this: enter image description here

> for i in 1:num_rows
> col_name = string("c", "$i")
> df[!, Symbol(col_name)] .= missing
> end
> 
> #After trying to insert values into specific cells:
> 
> ERROR: MethodError: convert(::Type{Union{}}, ::Float64) is ambiguous. Candidates:
> convert(::Type{T}, x::Number) where T<:Number in Base at number.jl:7
> convert(::Type{T}, x::Number) where T<:AbstractChar in Base at char.jl:184
> convert(::Type{Union{}}, x) in Base at essentials.jl:213
> convert(::Type{T}, arg) where T<:VecElement in Base at baseext.jl:19
> Possible fix, define
> convert(::Type{Union{}}, ::Number)

Upvotes: 1

Views: 321

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69949

You most likely want this:

julia> df = DataFrame(id=1:5)
5×1 DataFrame
 Row │ id
     │ Int64
─────┼───────
   1 │     1
   2 │     2
   3 │     3
   4 │     4
   5 │     5

julia> df.c1 = missings(Float64, nrow(df))
5-element Vector{Union{Missing, Float64}}:
 missing
 missing
 missing
 missing
 missing

julia> df
5×2 DataFrame
 Row │ id     c1
     │ Int64  Float64?
─────┼─────────────────
   1 │     1   missing
   2 │     2   missing
   3 │     3   missing
   4 │     4   missing
   5 │     5   missing

julia> df[2, :c1] = 12.5
12.5

julia> df
5×2 DataFrame
 Row │ id     c1
     │ Int64  Float64?
─────┼──────────────────
   1 │     1  missing
   2 │     2       12.5
   3 │     3  missing
   4 │     4  missing
   5 │     5  missing

Upvotes: 2

Related Questions