[英]How I can save an array as NetCDF file?
Another user helped me to build the following code which works perfectly.另一位用户帮助我构建了以下完美运行的代码。 With this code, I have an array with the sum_values (conditionally) of my initial data for each grid and year.
使用此代码,我有一个数组,其中包含每个网格和年份的初始数据的 sum_values(有条件地)。 I want to save the "summed_values_per_year" array as a NetCDF file.
我想将“summed_values_per_year”数组保存为 NetCDF 文件。 I tried multiple ways to do it, however, I am new to Python and I didn't make it.
我尝试了多种方法来做到这一点,但是,我是 Python 新手,但我没有成功。
Please share if you have any ideas and let me know what else I have to provide, like the attributes of an object.如果您有任何想法,请分享,并让我知道我还需要提供什么,例如对象的属性。 Thank you very much in advance.
非常感谢您提前。
file = netCDF4.Dataset ('/mnt/data/rcp45/tas/merged_rcp45/summed_values_per_year')
lat = file.variables['lat'][:]
lon = file.variables['lon'][:]
data = file.variables['tas'][:]
summed_values = np.zeros((14,16))
for grid_index, grid in enumerate(data):
for lon_index, lon_column in enumerate(grid):
for lat_index, value in enumerate(lon_column):
if 0 < value and value < 25:
summed_values[lon_index][lat_index] += value
n_years = data.shape[0] // 365
summed_values_per_year = np.zeros((n_years + 1, 14, 16))
for grid_index, grid in enumerate(data):
for lon_index, lon_column in enumerate(grid):
for lat_index, value in enumerate(lon_column):
if 0 < value and value < 25:
year = grid_index // 365
**summed_values_per_year** [year][lon_index][lat_index] += value
I would take a look at xarray .我会看看xarray 。 Specifically, see the docs on creating a dataset , and then on reading and writing files .
具体来说,请参阅有关创建数据集的文档,然后参阅有关 读取和写入文件的文档。
You can directly create an xarray dataset from summed_values_per_year(year, lon, lat)
like this:您可以直接从
summed_values_per_year(year, lon, lat)
创建一个 xarray 数据集,如下所示:
ds = xr.Dataset({
'summed_values_per_year': xr.DataArray(
summed_values_per_year,
dims=['year', 'lon', 'lat'],
coords=[range(nyears), lon, lat], # using the variables you defined
),
})
ds.to_netcdf("some/output/filepath.nc")
That said, it looks like what you're doing is to first mask the data to only include the values between 0 and 25, then group by year and sum.也就是说,看起来您正在做的是首先屏蔽数据以仅包含 0 到 25 之间的值,然后按年份分组并求和。 This can be done really easily in xarray:
这可以在 xarray 中非常容易地完成:
ds = xr.open_dataset(
'/mnt/data/rcp45/tas/merged_rcp45/summed_values_per_year'
)
summed_values_per_year = (
ds.where((ds.tas > 0) & (ds.tas < 25))
.groupby('time.year')
.sum(dim='time')
)
summed_values_per_year.to_netcdf("some/output/filepath.nc")
See the xarray docs on computation for more info.有关更多信息,请参阅有关 计算的 xarray 文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.