Julia:将数字字符串转换为float或int

时间:2015-10-30 16:39:07

标签: julia

我正在尝试将从数据库中提取的数字数据写入::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)
  ...

尝试直接转换数据并不出人意料地抛出同样的错误:

angular@2.0.0-alpha.41

鉴于我知道数据是数字的,有没有办法在推送之前将其转换成?

P.S。我使用的是0.4.0版本

3 个答案:

答案 0 :(得分:38)

您可以从字符串中parse(Float64,"1")。或者在矢量

的情况下
map(x->parse(Float64,x),stringvec)

将解析整个向量。

BTW考虑使用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]

答案 1 :(得分:7)

使用parse(Float64,"1")

详情请见:parse specification

答案 2 :(得分:0)

以前的答案很好,但是,我对它们进行了扩展:

#col1 = df[:,3]
col1 = ["1.2", "NA", "", Base.missing, "-1e3"]

# I do not like writing unreadable code like this:
col2 = map(x->(x=ismissing(x) ? "" : x; x=tryparse(Float64,x); isnothing(x) ? missing : x), col1)

如果原始数据是所有数字,则返回 Array {Float64,1}

5-element Array{Union{Missing, Float64},1}:
     1.2
      missing
      missing
      missing
 -1000.0

替代(解释):

function convert_to_float(column)
    new_column = map(x -> (
            x = ismissing(x) ? "" : x;  # no method matching tryparse(::Type{Float64}, ::Missing)
            x = tryparse(Float64, x);   # returns: Float64 or nothing
            isnothing(x) ? missing : x; # options: missing, or "", or 0.0, or nothing
            ), column)  # input 
    # returns Array{Float64,1} OR Array{Union{Missing, Float64},1}
    return new_column
end