Xarray在python中将单独的日期和小时维度合并为一个时间维度

问题描述

我有一个 xarray 数据集:

Jupyter cell output of xarray

如您所见,尺寸为(纬度、经度、步长(小时)、时间(天))。我想将小时和天数合并为一个,以便尺寸改为(纬度、经度、时间步长)。我该怎么做?

解决方法

创建一维时间维度和坐标

您可以使用 stack 方法创建时间和步长维度的多重索引。由于您的 valid_time 坐标已经具有正确的 datetime 维度,因此您还可以删除多索引坐标,只保留带有实际日期时间的 valid_time 坐标。

import numpy as np
import xarray as xr
import pandas as pd

# Create a dummy representation of your data
ds = xr.Dataset(
    data_vars={"a": (("x","y","time","step"),np.random.rand(5,5,3,24))},coords={
        "time": pd.date_range(start="1999-12-31",periods=3,freq="d"),"step": pd.timedelta_range(start="1h",freq="h",periods=24),},)
ds = ds.assign_coords(valid_time=ds.time + ds.step)

# Stack the time and step dims
stacked_ds = ds.stack(datetime=("time","step"))

# Drop the multiindex if you want to keep only the valid_time coord which
# contains the combined date and time information.
# Rename vars and dims to your liking.
stacked_ds = (
    stacked_ds.drop_vars("datetime")
    .rename_dims({"datetime": "time"})
    .rename_vars({"valid_time": "time"})
)
print(stacked_ds)
<xarray.Dataset>
Dimensions:  (time: 72,x: 5,y: 5)
Coordinates:
  * time     (time) datetime64[ns] 1999-12-31T01:00:00 ... 2000-01-03
Dimensions without coordinates: x,y
Data variables:
    a        (x,y,time) float64 0.1961 0.3733 0.2227 ... 0.4929 0.7459 0.4106

使时间坐标成为索引

像这样,我们创建了一个以连续日期时间序列为坐标的单一时间维度。然而,它不是index。对于某些方法,例如 resample,时间需要是一个索引。我们可以通过显式设置索引来解决这个问题:

stacked_ds.set_index(time="time")

然而,这将使“时间”成为变量而不是坐标。为了让它再次成为坐标,我们可以使用

stacked_ds.set_index(time="time").set_coords("time")

使用数据数组

您也可以在 Dataarray 上使用维度堆叠。但是,它们没有 rename_dimsrename_vars 方法。相反,您可以使用 swap_dimsrename

(
    ds.a.stack(datetime=("time","step"))
    .drop_vars("datetime")
    .swap_dims({"datetime": "time"})
    .rename({"valid_time": "time"})
).set_index(time="time")