如何在python中从另一个2D网格中对2D网格进行子集化?

时间:2016-08-03 21:39:29

标签: python arrays indexing

我在连续的美国网格化数据,我试图在特定区域选择一大块。

import numpy as np
from netCDF4 import Dataset
import matplotlib.pyplot as plt

filename = '/Users/me/myfile.nc'
full_data = Dataset(filename,'r')
latitudes = full_data.variables['latitude'][0,:,:] 
longitudes = full_data.variables['longitude'][0,:,:]
temperature = full_data.variables['temperature'][0,:,:]

所有三个变量都是二维矩阵形状(337,451)。我正在尝试执行以下操作以获取特定区域上的数据的子选择。

index = (latitudes>=44.0)&(latitudes<=45.0)&(longitudes>=-91.0)&(longitudes<=-89.0)
temp_subset = temperature[index]
lat_subset = latitudes[index]
lon_subset = longitudes[index]

我希望这三个变量都是二维的,但它们都会返回一个形状为(102,)的扁平数组。我尝试了另一种方法:

index2 = np.where((latitudes>=44.0)&(latitudes<=45.0)&(longitudes>=-91.0)&(longitudes<=-89.0))
temp = temperatures[index2[0],:]
temp2 = temp[:,index2[1]]
plt.imshow(temp2,origin='lower')
plt.colobar()

但我的数据看起来很不正确。有没有更好的方法从更大的网格中获取2D子网格?

enter image description here

1 个答案:

答案 0 :(得分:0)

Edub,

我建议查看numpy的矩阵索引文档,特别是http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#other-indexing-options。目前,您为索引提供了两个维度,但没有切片信息(导致只接收一维结果)。我希望这证明有用!