英文:
Julia: create empty DataFrame and then fill part of it with Float64 values
问题
以下是要翻译的内容:
我需要创建一个空的 DataFrame,然后只填充其中一些单元格的 Float64 值。
如果我在创建 DataFrame 时使用 "missing" 值来指示,然后当我想要插入值时就会出错。
如果我立即插入浮点值,就不会出现错误,但此时 DataFrame 不是空的。
也许问题是,如何立即将 DataFrame 转换为包含 "missing" 值?
英文:
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:
> 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)
答案1
得分: 2
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
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论