[英]Xarray merge separate day and hour dimensions into one time dimension in python
您可以使用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")
您也可以在 Dataarrays 上使用維度堆疊。 但是,它們沒有rename_dims
和rename_vars
方法。 相反,您可以使用swap_dims
和rename
:
(
ds.a.stack(datetime=("time", "step"))
.drop_vars("datetime")
.swap_dims({"datetime": "time"})
.rename({"valid_time": "time"})
).set_index(time="time")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.