从由纬度和经度定义的边界框中的数组中提取数据

问题描述 投票:0回答:1

我有“rh_irr”,它是一个大小为

744*171*162
的数组,其中171是纬度,162是经度,744是时间维度。我还有数组 lat 和 lon ,大小均为 171*162 ,并包含相应的数据纬度和经度。我需要提取经度 -115.3 到 -115.5 以及纬度 32.5 到 33.1 的边界框内的数据。

import numpy as np

# Define the latitude and longitude ranges
lat_min, lat_max = 32.5, 33.1
lon_min, lon_max = -115.5, -115.3

# Find the indices of latitudes and longitudes within the specified range
lat_indices = np.where((lat >= lat_min) & (lat <= lat_max))[0]
lon_indices = np.where((lon >= lon_min) & (lon <= lon_max))[1]

# Extract the data within the specified range
extracted_data = rh_irr[:, lat_indices, :][:, :, lon_indices]

# Print the shape of the extracted data
print("Shape of extracted data:", extracted_data.shape)

上面的代码执行,希望它能完成我想做的事情,但崩溃了。我们怎样才能提高内存效率呢?请建议是否还有其他更好的方法。

python geolocation bounding-box
1个回答
0
投票

np.where()
函数使用额外的内存来存储条件为
True
的索引,但它不会对内存使用产生显着影响。如果将布尔掩码直接应用于
rh_irr
数组来提取子集,它将避免不必要的内存分配。您可以使用 memory-profiler 模块来监控内存消耗。

import numpy as np

# Define the latitude and longitude ranges
lat_min, lat_max = 32.5, 33.1
lon_min, lon_max = -115.5, -115.3

# Create boolean masks for latitude and longitude
lat_mask = (lat >= min_lat) & (lat <= max_lat)
lon_mask = (lon >= min_lon) & (lon <= max_lon)

# Apply boolean masks directly on the array
selected_data = rh_irr[:, lat_mask, :][:, :, lon_mask]

# Check the shape of selected_data
print("Shape of selected_data:", selected_data.shape)
© www.soinside.com 2019 - 2024. All rights reserved.