Xray 无法将 ascii 数据加载到 netcdf 文件中

Xray not able to load ascii data into netcdf file

我正在使用 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)

使用您提供的更清晰的逻辑形式,我能够以这种方式加载您的 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')

此 returns 一个新的 netCDF 文件,格式如下:

ncdump -h tmp.nc
netcdf tmp {
dimensions:
    lat = 720 ;
    lon = 1440 ;
variables:
    double lat(lat) ;
    double lon(lon) ;
    double ascii_data(lat, lon) ;
}