我试图将从数据库中提取的数值数据写入Float64[]
。原始数据为::ASCIIString
格式,因此尝试将其推入数组会产生以下错误:
julia> push!(a, "1")
ERROR: MethodError: `convert` has no method matching convert(::Type{Float64}, ::ASCIIString)
This may have arisen from a call to the constructor Float64(...),
since type constructors fall back to convert methods.
Closest candidates are:
call{T}(::Type{T}, ::Any)
convert(::Type{Float64}, ::Int8)
convert(::Type{Float64}, ::Int16)
...
in push! at array.jl:432
毫不奇怪,尝试直接转换数据会引发相同的错误:
julia> convert(Float64, "1")
ERROR: MethodError: `convert` has no method matching convert(::Type{Float64}, ::ASCIIString)
This may have arisen from a call to the constructor Float64(...),
since type constructors fall back to convert methods.
Closest candidates are:
call{T}(::Type{T}, ::Any)
convert(::Type{Float64}, ::Int8)
convert(::Type{Float64}, ::Int16)
...
鉴于我知道数据是数字的,是否有办法在推送之前将其转换?
ps。我正在使用版本0.4.0
最佳答案
您可以使用字符串parse(Float64,"1")
。或在 vector 的情况下
map(x->parse(Float64,x),stringvec)
将解析整个 vector 。
顺便说一句,请考虑使用
tryparse(Float64,x)
而不是解析。如果字符串解析得不好,它将返回一个Nullable{Float64}
为null。例如:isnull(tryparse(Float64,"33.2.1")) == true
通常在解析错误的情况下会希望使用默认值:
strvec = ["1.2","NA","-1e3"]
map(x->(v = tryparse(Float64,x); isnull(v) ? 0.0 : get(v)),strvec)
# gives [1.2,0.0,-1000.0]
关于string - Julia:将数字字符串转换为float或int,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33440857/