问题:
我创建了一个NetCDF4文件,当使用xarray打开该文件时,会向感兴趣的变量引入高值,并且内核不断崩溃。当加载到MATLAB中时,我没有看到高值,这表明NetCDF4文件和xarray之间可能存在不兼容问题?
我就是这么做的:
我首先创建了一个NetCDF4文件,其中包括我感兴趣的变量:
from netCDF4 import Dataset
import numpy as np
import xarray as xr
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Create data
data_2_save = np.squeeze(np.float32(np.zeros([6,29947])))
data_2_save[0,1000:27300] = np.nan;
data_2_save[1,1010:27310] = np.nan;
data_2_save[2,1050:27350] = np.nan;
data_2_save[3,1000:27300] = np.nan;
data_2_save[4,900:27300] = np.nan;
data_2_save[5,100:27300] = np.nan;
# time range
t = np.float32(range(-2921,27026,1))
# for other dimension
d = np.arange(1,7)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# create NetCDF4 file
filename = 'test.nc'
dataset = Dataset(filename, 'w', format='NETCDF4_CLASSIC')
fillvalue = 999999
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# define dimensions
TIME_DIM = dataset.createDimension('TIME', None)
D_DIM = dataset.createDimension('D', np.size(d))
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# create variables
TIME = dataset.createVariable('TIME', np.float32, ('TIME',))
D = dataset.createVariable('D', np.int32, ('D',))
VAR = dataset.createVariable('VARIABLE', np.float32, ('TIME','D'),
fill_value=fillvalue)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# VAR
VAR.long_name = 'name'
VAR.valid_max = np.float32(np.nanmax(data_2_save))
VAR.valid_min = np.float32(np.nanmin(data_2_save))
VAR.coordinates = 'TIME D'
VAR.comment = ('A comment goes here')
# Time
time_unit_out= "days since 1950-01-01 00:00:00 UTC"
TIME.units = time_unit_out
TIME.long_name = 'analysis time'
TIME.standard_name = 'time'
TIME.valid_max = np.nanmax(t)
TIME.valid_min = np.nanmin(t)
TIME.axis = 'T'
TIME.calendar = 'gregorian'
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# D
D.standard_name = 'D'
D.valid_max = np.int32(np.round(np.nanmax(d)))
D.valid_min = np.int32(np.round(np.nanmin(d)))
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Save data into NetCDF
TIME[:] = t
D[:] = np.ndarray.tolist(d)
VAR[:] =np.transpose(data_2_save)
dataset.close()# and the file is written
然后我稍后加载文件并绘制如下:
import xarray as xr
data = xr.open_dataset('test.nc')
data.VARIABLE[:,1].plot()
然后要么内核崩溃,要么生成一个图。每次都会产生不同的情节,随机数字与我的预期(0.,nan(一起绘制。这些随机数可以是=~20000,>e+38并且有时=0。这些随机数往往位于变量数组的末尾,这里应该有NaN。有时不引入随机数。
我尝试过以下操作:
- '附件更新--全部'
- 在NetCDF4文件中创建变量时,尝试使用"np.int32"、"np.foat64"、"float">
- 创建NETCDF4文件时,将格式从"NETCDF-CLASSIC"更改为"NETCDF4">
版本
- Python 3.9
- 阵列0.20.1
- matplotlib 3.5.1
- netcdf4 1.5.7
- 数字1.21.5
由于使用pip和conda安装软件包时出现问题,我最近重新安装了Anaconda和软件包。
我已经用Spyder和Jupyter Notebook尝试过了,当两者都使用时就会发生这种情况。
我决定使用xarray而不是netCDF4包制作NetCDF文件。问题不再出现。