我正在使用xray python库将ascii文件中的所有数据添加到netcdf文件中。 ascii文件包含地球上每0.25度单元格的数据。
我可以创建所有lat / lon维度,但无法添加数据。 ascii文件位于:https://www.dropbox.com/s/lybu6yvm4ph7pcr/tmp.txt?dl=0
有人可以诊断代码并查看出现了什么问题吗?
import numpy, os, pdb, errno, sys, xray
NUM_LATS = 180.0
NUM_LONS = 360.0
inp_dir = 'C:\\Input\\'
out_dir = 'C:\\Output\\nc\\'
def make_dir_if_missing(d):
try:
os.makedirs(d)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
make_dir_if_missing(out_dir)
# Read ASCII File
fl_name = inp_dir+'tmp.txt'
ascii_fl = numpy.loadtxt(fl_name, delimiter=' ')
# Compute dimensions of nc file based on # rows/cols in ascii file
fl_res = NUM_LATS/ascii_fl.shape[0]
if fl_res != NUM_LONS/ascii_fl.shape[1]:
print 'Incorrect dimensions in ascii file'
sys.exit(0)
lon = numpy.arange(0.5, 360.5, fl_res)
lat = numpy.arange(-90.5, 89.5, fl_res)
lons, lats = numpy.meshgrid(lon,lat)
d = {}
d['latitudes'] = ('latitudes',lat)
d['longitudes'] = ('longitudes', lon)
d['data'] = (['latitudes','longitudes'], ascii_fl)
dset = xray.Dataset(d)
dset
out_nc = out_dir+os.path.basename(inp_dir+'tmp.txt')[:-4]+'.nc'
dset.to_netcdf(out_nc)
答案 0 :(得分:1)
使用您提供的更简洁的逻辑形式,我能够加载您的ascii数据并以这种方式将其保存到netCDF文件中:
import numpy as np
import xray
# This was logic from the OP
NUM_LATS = 180.0
NUM_LONS = 360.0
ascii_data = np.loadtxt('tmp.txt', delimiter=' ')
fl_res = NUM_LATS / ascii_data.shape[0]
if fl_res != NUM_LONS / ascii_data.shape[1]:
raise ValueError('Incorrect dimensions in ascii file')
lon = np.arange(0.5, 360.5, fl_res)
lat = np.arange(-90.5, 89.5, fl_res)
# Create an empty Dataset
ds = xray.Dataset()
# Add coordinate variables
ds['lon'] = ('lon', lon)
ds['lat'] = ('lat', lat)
# Add data (coordinates are automatically mapped)
ds['ascii_data'] = (('lat', 'lon'), ascii_data)
# Write to a netcdf
ds.to_netcdf('tmp.nc')
这将返回一个具有以下格式的新netCDF文件:
ncdump -h tmp.nc
netcdf tmp {
dimensions:
lat = 720 ;
lon = 1440 ;
variables:
double lat(lat) ;
double lon(lon) ;
double ascii_data(lat, lon) ;
}