0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Xarrayで多次元データを扱う備忘録

Posted at

業務で急に多次元データ(netcdfデータ 緯度・経度・時刻・標高)を扱う必要があったので、備忘録的に整理します。
ここでは xarray を使って 緯度・経度・時刻の3次元気温データ を生成し、分析・可視化まで行います。
データは20〜30℃の範囲でランダムに生成した架空データです。

Xarrayのインポート

import pandas as pd
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt

データセットの作成

# 次元
time = pd.date_range("2025-01-01", periods=10, freq="D")
lat = np.linspace(30, 40, 5)   # 緯度5地点
lon = np.linspace(130, 140, 6) # 経度6地点

# 架空の気温データ(20〜30℃)
temperature_data = 20 + 10 * np.random.rand(len(time), len(lat), len(lon))

# Dataset作成
ds = xr.Dataset(
    {
        "temperature": (("time", "lat", "lon"), temperature_data)
    },
    coords={
        "time": time,
        "lat": lat,
        "lon": lon
    },
    attrs={
        "title": "Synthetic Temperature Dataset",
        "description": "Mock temperature data for testing",
        "units": "Celsius",
        "version": "test"
    }
)

参考 既存のnetcdfデータの読み込み

ds = xr.open_dataset(
    "test.nc",
    engine="netcdf4"
)

データ構造の確認

ds

Xarrayデータの諸情報の確認

ds          # データセット全体
ds.dims     # ディメンション情報
ds.variables # 変数情報
ds.attrs    # グローバル属性

値の参照

# 特定時刻の全地点
ds['temperature'].isel(time=0)

# 特定地点の全時刻
ds['temperature'].isel(lat=0, lon=0)

# 最大値・平均値・中央値
ds['temperature'].max()
ds['temperature'].mean()
ds['temperature'].median()

# 特定地点の最大値
ds['temperature'].isel(lat=0, lon=0).max()

次元を固定した最大値の確認

ds['temperature'].isel(time=0).max()
ds['temperature'].isel(lat=0,lon=0).max()

可視化例

一次元の可視化

日ごと

ds["temperature"].isel(lat=0, lon=0).plot()

image.png

週ごとの平均

(
    ds.
    resample({'time':"1w"}).
    mean(dim=['time','lat','lon']).
    temperature.
    plot(marker='o')
)

image.png

月毎の平均

(
    ds
    .groupby(ds.time.dt.month)
    .mean(dim=['time', 'lat', 'lon'])  
    .temperature
    .plot(marker='o')
)

image.png

二次元(地図表示)

ds["temperature"].isel(lat=0, lon=0).plot()

image.png

季節を跨いだ比較(1月1日と12月31日の差)

seasonal_change = (ds.temperature.sel(time="2025-01-01") - ds.temperature.sel(time='2025-12-31'))

seasonal_change.plot()

image.png

まとめ

  • xarray は多次元データの分析に便利で、座標付きで計算や集計が可能
  • groupby や resample を使うと、月・週などの集計も簡単。
  • .plot() で時系列・空間分布どちらも可視化できる

これをベースに、実データ(NetCDFやGRIB)でも同じ操作が可能です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?