2017-05-09 63 views
2

我有两种格式(时间,lats,lons)的液态水当量厚度月度全球网格数据集。两者具有相同的空间和时间分辨率。我想关联它们,但numpy.corrcoef()只适用于二维数组,而不适用于三维。 所以我想关联整个时间序列的两个变量的同一个网格点(x,y)。事实上,我想要一个具有相关系数网格的新文件。关联python中的网格数据集

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放到一个新的阵列在正确的位置?

+1

你能用[最小,完整和可验证的例子](http://stackoverflow.com/help/mcve)更新你的问题吗? – Kasramvd

+0

这是你需要的信息@Kasramvd? –

回答

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[:,:] 

改进建议非常受欢迎!

+0

或者,您可以将系数矩阵初始化为'corrcoefMatrix_gfzjpl = np.zeros([len(lats),len(lons)])'',然后将数据存储在double for-loop中,作为corrcoefMatrix_gfzjpl [x,y] =温度[0,1]'。 – N1B4