NetCDF4文件处理
下载MACA v2的netcdf4格式数据
使用xarray读取和处理netcdf4格式数据
将netcdf4格式数据导出为.csv格式
将netcdf4格式数据导出为.tif格式
参考链接
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 处理netcdf4文件所要用到的包
import xarray as xr
import rioxarray
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import seaborn as sns
import geopandas as gpd
import earthpy as et
# 统计图绘制选项
sns.set(font_scale=1.3)
sns.set_style("white")
文件读取
.nc文件名的含义
agg_macav2metdata_tasmax_BNU-ESM_r1i1p1_historical_1950_2005_CONUS_monthly
agg_macav2metdata:MACA v2版本,降尺度到美国大陆
tasmax:数据项为最高温度
BNU-ESM:产生该原始数据的模式名称
historical:数据为1950-2005年的历史预测数据
CONUS:数据范围为美国(CONtinental United States boundary)
monthly:数据的时间分辨率为月份
# MACAv2数据连接
data_path = "http://thredds.northwestknowledge.net:8080/thredds/dodsC/agg_macav2metdata_tasmax_BNU-ESM_r1i1p1_historical_1950_2005_CONUS_monthly.nc"
# 打开数据
with xr.open_dataset(data_path) as file_nc:
# 使用 rio.write _ crs,确保数据的坐标系在整个分析过程中都保持不变
max_temp_xr = file_nc.rio.write_crs(file_nc.rio.crs, inplace=True)
# 查看数据对象
max_temp_xr
# 读取数据的坐标系统信息
climate_crs = max_temp_xr.rio.crs
climate_crs
CRS.from_wkt('GEOGCS["undefined",DATUM["undefined",SPHEROID["undefined",6378137,298.257223563]],PRIMEM["undefined",0],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AXIS["Longitude",EAST],AXIS["Latitude",NORTH]]')
# 查看前五行数据
max_temp_xr['air_temperature']['lat'].values[:5]
# 输出经纬度的最大值和最小值
print("The min and max latitude values in the data is:",
max_temp_xr["air_temperature"]["lat"].values.min(),
max_temp_xr["air_temperature"]["lat"].values.max())
print("The min and max longitude values in the data is:",
max_temp_xr["air_temperature"]["lon"].values.min(),
max_temp_xr["air_temperature"]["lon"].values.max())
The min and max latitude values in the data is: 25.063077926635742 49.39602279663086
The min and max longitude values in the data is: 235.22784423828125 292.93524169921875
# 查看数据的时间范围
print("The earliest date in the data is:", max_temp_xr["air_temperature"]["time"].values.min())
print("The latest date in the data is:", max_temp_xr["air_temperature"]["time"].values.max())
The earliest date in the data is: 1950-01-15 00:00:00
The latest date in the data is: 2005-12-15 00:00:00
# 查看数据记录的总条数,本数据集共672条,即672个月
max_temp_xr["air_temperature"]["time"].values.shape
(672,)
# 查看数据的坐标系统信息
max_temp_xr["crs