我有两个月度全球网格化液体水当量厚度数据集(时间,拉特,长度)。两者具有相同的空间和时间分辨率。我想关联它们,但numpy.corrcoef()
仅适用于2D数组,而不适用于3D。
所以我想关联整个时间序列的两个变量的相同网格点(x,y)。实际上我想要一个带有相关系数网格的新nc文件。
import numpy as np
from netCDF4 import Dataset
wdir = '.../Data/'
# read GRACE NCs
GRACE_GFZ = Dataset(wdir+'GRACE/GRCTellus.GFZ.200204_201607.nc','r')
GRACE_JPL = Dataset(wdir+'GRACE/GRCTellus.JPL.200204_201607.nc','r')
两个变量(gfz和jpl)在相同位置具有相同数量的缺失值。
GRACE_GFZ.variables['lwe_thickness']
<type 'netCDF4._netCDF4.Variable'>
float32 lwe_thickness(time, lat, lon)
long_name: Liquid_Water_Equivalent_Thickness
units: cm
_FillValue: 32767.0
missing_value: 32767.0
unlimited dimensions: time
current shape = (155, 72, 144)
filling off
GRACE_JPL.variables['lwe_thickness']
<type 'netCDF4._netCDF4.Variable'>
float32 lwe_thickness(time, lat, lon)
long_name: Liquid_Water_Equivalent_Thickness
units: cm
_FillValue: 32767.0
missing_value: 32767.0
unlimited dimensions: time
current shape = (155, 72, 144)
filling off
因为它们具有相同的时间和空间分辨率,所以两者都可以使用时间,经度和纬度。
time = GRACE_GFZ.variables['time'][:]
lons = GRACE_GFZ.variables['lon'][:]
lats = GRACE_GFZ.variables['lat'][:]
gfz = GRACE_GFZ.variables['lwe_thickness'][:]
jpl = GRACE_JPL.variables['lwe_thickness'][:]
在这里,我想通过网格并将corrcoef放入数组中。这给了我一堆2x2矩阵。
test = []
for x in range(len(lats)):
for y in range(len(lons)):
print(np.corrcoef(gfz[:,x,y],jpl[:,x,y]))
如何将每个点的corrcoef放入正确位置的新阵列?
答案 0 :(得分:0)
我用以下方法克服了我的问题:
temp =[]
corrcoefMatrix_gfzjpl = [[0 for i in range(len(lons))] for j in range(len(lats))]
for x in range(len(lats)):
for y in range(len(lons)):
temp = np.corrcoef(gfz[:,x,y],jpl[:,x,y])
corrcoefMatrix_gfzjpl[x][y] = temp[0,1]
corrcoefMatrix_gfzjpl = np.squeeze(np.asarray(corrcoefMatrix_gfzjpl))
基本上我制作了一个包含零的矩阵,并用corrcoef矩阵中的相关系数值替换它们。我为每个网格单元执行了此操作,方法是通过lats和lons,每个网格使用for循环。 之后我创建了一个新的netcdf文件,定义了所有维度和变量。
nc_data.createDimension('lat', len(lats))
nc_data.createDimension('lon', len(lons))
nc_data.createDimension('data', 1)
latitudes = nc_data.createVariable('latitude', 'f4', ('lat',))
longitudes = nc_data.createVariable('longitude', 'f4', ('lon',))
corrcoef_gfzjpl = nc_data.createVariable('corrcoef_gfzjpl', 'f4', ('lat', 'lon', 'data'), fill_value=-999.0)
latitudes.units = 'degree_north'
longitudes.units = 'degree_east'
latitudes[:] = np.arange(-90, 90, 180./len(lats))
longitudes[:] = np.arange(0, 360, 360./len(lons))
corrcoef_gfzjpl[:,:] = corrcoefMatrix_gfzjpl[:,:]
非常欢迎有关改进的建议!