关于 xarray
xarray 是面向科学与地球科学数据分析的 Python 工具,使用带标签的多维数组处理数据集。它支持 NetCDF、Zarr 和 Dask 工作流,适合气候数据的筛选、聚合与分析。
主要功能
- 01处理带标签的多维数组
- 02读写 NetCDF 与 Zarr
- 03按坐标和索引筛选数据
- 04执行分组、重采样与统计
- 05通过 Dask 延迟处理大型数据
适用场景
- 01按时间或地理区域分析气候数据
- 02计算月度气候态与异常值
- 03分块处理大型数据集
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ steadfastasart/ geoscience-skills --skill xarray安装后在 Claude Code 中输入/xarray确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/computation.mdio_formats.mdscripts/climate_analysis.py详细介绍
xarray - 多维地球科学数据
快速参考
import xarray as xr
# Read
ds = xr.open_dataset('data.nc')
# Access data
temp = ds['temperature'] # DataArray
values = temp.values # numpy array
df = ds.to_dataframe() # pandas DataFrame
# Structure info
print(ds) # Overview
print(ds.dims) # Dimensions
print(ds.data_vars) # Variables
# Write
ds.to_netcdf('output.nc')
主要类
| 类 | 用途 |
|---|---|
Dataset | 一组对齐的 DataArray(类似 NetCDF 文件) |
DataArray | 带有标记维度的单个变量 |
Coordinates | 维度标签(time、lat、lon) |
基本操作
选择数据
# By coordinate value
temp_jan = ds['temperature'].sel(time='2020-01-15')
temp_region = ds['temperature'].sel(lat=slice(-30, 30), lon=slice(-60, 60))
# Nearest value
temp_point = ds['temperature'].sel(lat=35.5, lon=-120.3, method='nearest')
# By index
temp_first = ds['temperature'].isel(time=0)
计算统计量
temp = ds['temperature']
temp_mean_time = temp.mean(dim='time') # Spatial map
temp_mean_space = temp.mean(dim=['lat', 'lon']) # Time series
# Area-weighted mean
import numpy as np
weights = np.cos(np.deg2rad(ds.lat))
temp_weighted = temp.weighted(weights).mean(dim=['lat', 'lon'])
分组和重采样
temp = ds['temperature']
# Temporal aggregations
monthly_mean = temp.groupby('time.month').mean()
annual_mean = temp.groupby('time.year').mean()
# Climatology and anomalies
climatology = temp.groupby('time.month').mean('time')
anomalies = temp.groupby('time.month') - climatology
# Resample time series
monthly = temp.resample(time='1M').mean()
rolling_30d = temp.rolling(time=30, center=True).mean()
创建新数据集
import numpy as np
import pandas as pd
times = pd.date_range('2020-01-01', periods=365, freq='D')
lats = np.linspace(-90, 90, 180)
lons = np.linspace(-180, 180, 360)
da = xr.DataArray(
data=np.random.randn(365, 180, 360),
dims=['time', 'lat', 'lon'],
coords={'time': times, 'lat': lats, 'lon': lons},
attrs={'units': 'degC', 'long_name': 'Temperature'}
)
ds = xr.Dataset({'temperature': da})
ds.to_netcdf('output.nc')
掩码
temp_warm = temp.where(temp > 20) # Mask by condition
temp_clipped = temp.where(temp > 0, 0) # Replace negative with 0
tropics = (ds.lat > -23.5) & (ds.lat < 23.5)
temp_tropics = temp.where(tropics, drop=True) # Mask by coordinate
大型数据集(Dask)
# Open with chunking (lazy loading)
ds = xr.open_dataset('large_file.nc', chunks={'time': 100})
ds = xr.open_mfdataset('data_*.nc', chunks='auto')
# Operations are lazy until .compute()
result = ds['temperature'].mean(dim='time').compute()
何时使用及替代方案
| 工具 | 最适用场景 | 局限性 |
|---|---|---|
| xarray | 带标签的多维数组、NetCDF/Zarr、Dask 集成 | 对 numpy 新手而言有一定学习门槛 |
| iris | Met Office 气候工作流、UGRID 网格支持 | 社区规模较小,惯例偏向英国 |
| CDO | 快速执行命令行气候数据操作 | 非 Python 原生,定制分析能力有限 |
| NCO | 快速操作 NetCDF 文件和进行算术运算 | 仅支持命令行,无可视化功能 |
在以下情况使用 xarray: 需要处理带标签的维度、无缝进行 NetCDF/Zarr I/O、 执行分组/重采样操作,或基于 Dask 并行处理大型数据集。
在以下情况考虑替代方案: 需要快速一次性通过命令行操作 NetCDF 文件(使用 CDO/NCO),或在使用 UGRID 网格的 Met Office 生态系统中工作 (使用 iris)。
常见工作流
通过时间聚合分析气候数据
- 使用
xr.open_dataset()打开 NetCDF 数据集(数据量较大时使用chunks=) - 使用
print(ds)查看维度、坐标和变量 - 使用
.sel(lat=slice(), lon=slice())选择感兴趣的区域 - 使用
.groupby('time.month').mean('time')计算气候态 - 从数据中减去气候态,计算距平
- 使用余弦纬度权重计算面积加权空间平均值
- 重采样到所需的时间分辨率(月度、年度)
- 使用
.to_netcdf()将结果保存为 NetCDF
常见问题
| 问题 | 解决方案 |
|---|---|
| 内存错误 | 使用 chunks= 延迟加载 |
| 时间解码失败 | 使用 decode_times=False,然后手动解码 |
| 缺少坐标 | 检查 ds.coords 和 ds.dims |
| 对齐错误 | 检查坐标值是否匹配 |
参考资料
脚本
- scripts/climate_analysis.py - 气候数据分析
评论
支持 Markdown