如何在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})
答案 0 :(得分:0)
我不知道如何使用包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不再需要这样做了。