scipy 从NetCDF文件读取和插值数据引发形状不匹配错误

epfja78i  于 2023-04-21  发布在  Etcd
关注(0)|答案(1)|浏览(221)

我有一个netcdf文件,其中包含纬度,经度和温度的数据。温度的纬度和经度尺寸为103x61。我想通过应用最近的插值将这个103x61网格调整为70x70。下面是我的代码:

import numpy as np
from netCDF4 import Dataset
from scipy.interpolate import griddata

# load data from netCDF file
nc_file = Dataset('data.nc', 'r')
lat = nc_file.variables['lat'][:]
lon = nc_file.variables['lon'][:]
temp = nc_file.variables['temp'][:]

# create new grid
new_lat = np.linspace(lat.min(), lat.max(), 80)
new_lon = np.linspace(lon.min(), lon.max(), 80)
new_lat, new_lon = np.meshgrid(new_lat, new_lon)

# flatten lat, lon, and temp arrays
lat_flat = lat.flatten()
lon_flat = lon.flatten()
temp_flat = temp.flatten()

# interpolate to new grid
new_temp = griddata((lat_flat, lon_flat), temp_flat, (new_lat, new_lon), method='linear')

# save new_temp to npy file
np.save('new_temp.npy', new_temp)

但这会产生以下错误:
ValueError:shape mismatch:对象不能广播到单个形状。形状(103,)的arg 0和形状(61,)的arg 1之间不匹配。
我知道有一个高度和宽度之间的不匹配,但我不能从任何一方裁剪数据,以适应正方形网格,然后插入它。有没有办法绕过这个错误?

41zrol4v

41zrol4v1#

我是这样解决的:

import xarray as xr
import numpy as np

temp = xr.open_dataset('data.nc')['temp']

lat = temp['latitude'].values
lon = temp['longitude'].values
new_lat = np.linspace(np.min(lat), np.max(lat), 80)
new_lon = np.linspace(np.min(lon), np.max(lon), 60)

new_temp = temp.interp(latitude=new_lat, longitude=new_lon, method='nearest')

new_temp = new_temp.to_numpy()
np.save('new_temp.npy', new_temp)

相关问题