我正在尝试将从数据库中提取的数字数据写入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
Run Code Online (Sandbox Code Playgroud)
试图直接转换数据不出所料引发同样的错误:
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)
...
Run Code Online (Sandbox Code Playgroud)
鉴于我知道数据是数字的,有没有办法在推送之前将其转换?
ps我使用的是0.4.0版本
Dan*_*etz 38
你可以parse(Float64,"1")从一个字符串.或者在矢量的情况下
map(x->parse(Float64,x),stringvec)
Run Code Online (Sandbox Code Playgroud)
将解析整个向量.
BTW考虑使用tryparse(Float64,x)而不是解析.它返回一个Nullable {Float64},在字符串不能很好地解析的情况下为null.例如:
isnull(tryparse(Float64,"33.2.1")) == true
Run Code Online (Sandbox Code Playgroud)
并且通常在解析错误的情况下需要默认值:
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]
Run Code Online (Sandbox Code Playgroud)