【问题标题】:Writing char array to NetCDF file with julia使用 julia 将 char 数组写入 NetCDF 文件
【发布时间】:2018-02-16 14:55:41
【问题描述】:

如何使用 julia 在 NetCDF 文件中添加字符数组?下面是一个代码示例。首先,它已经给出了写入字符串数组的错误,所以可能有问题。但实际上,我需要“国家”为 Char 类型。如何将字符串数组更改为 Char 以在 NetCDF 中使用?这似乎与此问题(https://github.com/JuliaLang/julia/issues/17694)有关,但我不知道如何解决它。

例子:

using NetCDF
filename="test_netcdf_string.nc"
# Define some attributes
varatts = Dict("longname" => "number of citizens","units" => "million")
timeatts = Dict("longname" => "Time","units"    => "year")
nameatts = Dict("longname" => "Country name")

#Add some random data
time_data=collect(2014:2017)
countries=["Italy ","Germany", "France "]
cit_numbers=rand(5:100,size(countries,1),size(time_data,1))

#Create variable in netcdf
nccreate(filename, "citizens", "country", countries, nameatts,
"time", time_data, timeatts, atts=varatts)

ERROR: MethodError: no method matching nc_put_vara_x(::NetCDF.NcVar{Float64,1,6}, ::Array{UInt64,1}, ::Array{UInt64,1}, ::Array{String,1})

【问题讨论】:

    标签: julia netcdf


    【解决方案1】:

    我不确定如何使用包 NetCDF.jl 执行此操作,但这里有一种使用 julia 包 NCDatasets.jl 的方法。

    using NCDatasets
    
    filename="test_netcdf_string.nc"
    
    time_data=collect(2014:2017)
    countries=["Italy ","Germany", "France "]
    cit_numbers=rand(5:100,size(countries,1),size(time_data,1))
    
    ds = Dataset(filename,"c")
    # define the dimensions
    defDim(ds,"countries",length(countries))
    defDim(ds,"time",length(time_data))
    
    # define the variables
    nccit_numbers = defVar(ds,"cit_numbers",Float64,("countries","time"))
    nccountries = defVar(ds,"countries",String,("countries",))
    nctime = defVar(ds,"time",Float64,("time",))
    
    # define the attributes
    nccountries.attrib["longname"] = "Country name"
    # add more attributes...
    
    nccountries[:] = countries
    nccit_numbers[:] = cit_numbers
    nctime[:] = time_data
    
    # closing the file to make sure the data is saved
    close(ds)
    

    运行 julia 命令Dataset(filename) 返回:

    Dataset: test_netcdf_string.nc
    Group: /
    
    Dimensions
       countries = 3
       time = 4
    
    Variables
      cit_numbers   (3 × 4)
        Datatype:    Float64
        Dimensions:  countries × time
    
      countries   (3)
        Datatype:    String
        Dimensions:  countries
        Attributes:
         longname             = Country name
    
      time   (4)
        Datatype:    Float64
        Dimensions:  time
    

    如果有人可以为包 NetCDF.jl 添加答案,这将很有帮助。

    请注意,从版本 4 开始,NetCDF 库已将字符串列表(或数组)写入 NetCDF 文件。您会发现很多关于 NetCDF 库 3 的文档,其中您只能编写向量(或数组) ) 的单个字符。在这种情况下,您需要使所有国家/地区名称的长度相等(例如,通过用空格或空字符填充它们)并将所有这些名称组合成一个矩阵。幸运的是,NetCDF 4 不再需要这样做。

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 2021-02-24
    • 2021-05-09
    相关资源
    最近更新 更多