【问题标题】:Julia: Convert numeric string to float or intJulia:将数字字符串转换为浮点数或整数
【发布时间】:2015-10-30 16:39:06
【问题描述】:

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

鉴于我知道数据是数字,有没有办法可以在推送之前对其进行转换?

附言我使用的是 0.4.0 版

【问题讨论】:

  • 顺便说一句,考虑使用tryparse(Float64,x) 而不是parse。它返回一个 Nullable Float,在字符串解析不好的情况下为 null。
  • 好建议,干杯。顺便说一句,如果你想写一个答案,我会接受它,否则我会在一两天内为了完整性而写一些东西。

标签: string floating-point type-conversion julia


【解决方案1】:

您可以从字符串中parse(Float64,"1")。或者在向量的情况下

map(x->parse(Float64,x),stringvec)

将解析整个向量。

顺便说一句,考虑使用tryparse(Float64,x) 而不是解析。它返回一个Nullable{Float64},如果字符串解析不好,它为空。例如:

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]

【讨论】:

  • 2021年评论:Nullable{T}是什么?看起来应该是Union{Nothing,T}?现在isnull 应该是isnothing(或=== nothing)吗?
【解决方案2】:

使用parse(Float64,"1")

查看更多信息:parse specification

【讨论】:

【解决方案3】:

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

#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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    • 2011-11-25
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    相关资源
    最近更新 更多