GPM(Global Precipitation Measurement)降水数据是由全球降水测量任务提供的高分辨率全球降水数据集。GPM任务由NASA和JAXA(日本宇宙航空研究开发机构)主导,旨在提供全球范围内的降水观测数据,以改进天气预测、气候研究和自然灾害监测。
常用工具包括Python、MATLAB和GIS软件,NASA和JAXA也提供专用工具和API。
注意改数据在处理时需要transpose一下,不然无法可视化出来。
最近下载了多年的daily降水数据,官网下载下来的gpm数据是一天一个文件,在批量处理时频繁开关文件效率低,所以将多个文件合并。我下载的是0.1°×0.1°网格的GPM(Global Precipitation Measurement)-IMERG-Final-V07逐日降水资料。
我是先把一年的合并,再合并多年的。
import xarray as xr
import glob
import os
from datetime import datetime# 配置路径参数
input_dir = r"F:\GPM-processed\merged"
output_path = r"F:\GPM-processed\GPM_2001-2020_summer_daily.nc"
file_pattern = "*.nc"# 获取并排序文件列表
def extract_date(filename):
"""修正后的日期提取函数"""
basename = os.path.basename(filename)
#parts = basename.split(".")
#date_segment = parts[4] # 正确索引位置
#return datetime.strptime(date_segment.split("-")[0], "%Y%m%d")
year_str = basename.split("_")[1] # 根据实际文件名结构调整索引
return int(year_str)
files = sorted(glob.glob(os.path.join(input_dir, file_pattern)),
key=lambda x: extract_date(x))
# 验证文件数量
#print(f"发现 {len(files)} 个文件,预期92个")
#assert len(files) == 92, "文件数量不符合夏季天数"
print(f"发现 {len(files)} 个文件,预期20个")
assert len(files) == 20, "文件数量不符合夏季天数"# 自定义预处理函数
def preprocess(ds):
#filename = ds.encoding["source"]
#date_str = os.path.basename(filename).split(".")[4].split("-")[0]
#new_time = datetime.strptime(date_str, "%Y%m%d")
#return ds.assign_coords(time=[new_time]).isel(time=0)
year = ds.time.dt.year.item() # 假设每个文件包含单一年度数据
start_date = f"{year}-06-01"
end_date = f"{year}-08-31"
new_time = xr.date_range(start_date, end_date, freq="D")
return ds.assign_coords(time=new_time)# 合并数据集
combined = xr.open_mfdataset(
files,
combine="nested",
concat_dim="time",
preprocess=preprocess,
parallel=True,
chunks={"time": 10}
)
# 保存合并结果
combined.to_netcdf(output_path)
print(f"合并完成!文件已保存至:{output_path}")合并多年数据。
# 获取并排序文件列表
def extract_year(filename):
"""从文件名中提取年份"""
basename = os.path.basename(filename)
# 假设文件名类似 GPM_2001_summer_daily.nc
year_str = basename.split("_")[1] # 根据实际文件名结构调整索引
return int(year_str)
files = sorted(glob.glob(os.path.join(input_dir, file_pattern)),
key=lambda x: extract_year(x))
# 验证文件数量
print(f"发现 {len(files)} 个文件,预期20个")
assert len(files) == 20, "文件数量不符合年度数量"
# 自定义预处理函数
def preprocess(ds):
"""统一时间坐标处理"""
# 从文件名提取年份
filename = ds.encoding["source"]
year = extract_year(filename)
# 重建时间坐标
start_date = f"{year}-06-01"
end_date = f"{year}-08-31"
new_time = xr.date_range(start_date, end_date, freq="D")
# 确保时间维度与数据对齐
if len(new_time) != len(ds.time):
raise ValueError(f"时间维度不匹配:文件 {filename} 的时间长度为 {len(ds.time)},预期为 {len(new_time)}")
return ds.assign_coords(time=new_time)
# 合并数据集
combined = xr.open_mfdataset(
files,
combine="nested",
concat_dim="time",
preprocess=preprocess,
parallel=True,
chunks={"time": 366} # 按年分块
)
# 优化元数据
combined.time.attrs.update({
"long_name": "Time",
"description": "Daily data from June to August"
})
# 配置输出编码
encoding = {
"precipitation": {
"zlib": True,
"complevel": 5,
"dtype": "float32",
"_FillValue": -9999.0
},
"time": {"dtype": "int32", "units": "days since 2001-01-01"}
}
# 保存合并结果
combined.to_netcdf(
output_path,
encoding=encoding,
unlimited_dims=["time"]
)
print(f"合并完成!文件已保存至:{output_path}")
# 验证结果
print("\n合并后数据集摘要:")
print(xr.open_dataset(output_path))
print出来看看。
import xarray as xr
gpm = xr.open_dataset("C:/Users/lenovo/Desktop/GPM_2001-2020_summer_daily.nc")
print(gpm)输出结果:
<xarray.Dataset> Size: 2GB
Dimensions: (time: 1840, bnds: 2, lon: 668, lat: 366)
Coordinates:
* lon (lon) float64 5kB 68.95 69.05 69.15 ... 135.4 135.6 135.6
* lat (lat) float64 3kB 17.85 17.95 18.05 ... 54.15 54.25 54.35
* time (time) datetime64[ns] 15kB 2001-06-01 ... 2020-08-31
Dimensions without coordinates: bnds
Data variables:
time_bnds (time, bnds) datetime64[ns] 29kB ...
precipitation (time, lon, lat) float32 2GB ...
Attributes: (12/13)
CDI: Climate Data Interface version 1.9.8 (https://mpimet.mpg...
Conventions: CF-1.6
BeginDate: 2001-06-01
BeginTime: 00:00:00.000Z
EndDate: 2001-06-01
EndTime: 23:59:59.999Z
... ...
InputPointer: 3B-HHR.MS.MRG.3IMERG.20010601-S000000-E002959.0000.V07B....
title: GPM IMERG Final Precipitation L3 1 day 0.1 degree x 0.1 ...
DOI: 10.5067/GPM/IMERGDF/DAY/07
ProductionTime: 2023-12-18T02:18:11.513Z
history_L34RS: 'Created by L34RS v1.4.4 @ NASA GES DISC on October 25 2...
CDO: Climate Data Operators version 1.9.8 (https://mpimet.mpg...
Process finished with exit code 0
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。