mcpField
X
xarray

xarray

github.com/steadfastasartデータ・データベース7483 回インストール7 週間前に更新
リポジトリ

xarray について

xarrayは、ラベル付き多次元配列を扱う科学・地球科学向けのPythonツールです。NetCDFやZarrの入出力とDaskによる処理に対応し、気候データの抽出や集計に使えます。

主な機能

  1. 01ラベル付き多次元配列の操作
  2. 02NetCDFとZarrの読み書き
  3. 03座標やインデックスによるデータ選択
  4. 04グループ化、リサンプリング、統計計算
  5. 05Daskによる大規模データの遅延処理

活用シーン

  1. 01時間や地域ごとの気候データ分析
  2. 02月別気候値と偏差の計算
  3. 03大規模データセットの分割処理

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/steadfastasart/geoscience-skills --skill xarray

インストール後、Claude Code で/xarrayを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

references/
computation.md
io_formats.md
scripts/
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'])
GroupBy とリサンプリング
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()
新しい Dataset の作成
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英国気象庁の気候ワークフロー、UGRID メッシュのサポートコミュニティが小さく、英国中心の規約
CDO高速なコマンドラインでの気候データ操作Python ネイティブではなく、カスタム分析に制限がある
NCONetCDF ファイルの手早い操作と算術演算コマンドライン専用で、可視化機能がない

次の場合は xarray を使用してください。 ラベル付きの次元処理、シームレスな NetCDF/Zarr の I/O、groupby/リサンプリング操作、または大規模データセットの Dask による並列処理が必要な場合です。

次の場合は代替ツールを検討してください。 NetCDF ファイルに対する単発のコマンドライン操作を高速に行いたい場合(CDO/NCO を使用)、または UGRID メッシュを使う英国気象庁のエコシステムで作業する場合(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 を確認する
アラインメントエラー座標値が一致しているか確認する

参考資料

  • I/O 形式 - NetCDF、Zarr、その他の形式
  • 計算 - 集約および分析の方法

スクリプト

コメント