簡體   English   中英

xarray:將時間片“插入”到數據集或數據數組中的最佳方法

[英]xarray: best way to "insert" a time slice into a dataset or dataarray

我有一個 3 維xarray數據集,其維度為xytime 假設我知道在時間步長n缺少觀測值,那么插入沒有數據值的時間片的最佳方法是什么?

這是一個工作示例:

import xarray as xr
import pandas as pd

x = xr.tutorial.load_dataset("air_temperature")

# assuming this is the missing point in time (currently not in the dataset)
missing = "2014-12-31T07:00:00"

# create an "empty" time slice with fillvalues
empty = xr.full_like(x.isel(time=0), -3000)

# fix the time coordinate of the timeslice
empty['time'] = pd.date_range(missing, periods=1)[0]

# before insertion
print(x.time[-5:].values)

# '2014-12-30T18:00:00.000000000' '2014-12-31T00:00:00.000000000'
#  '2014-12-31T06:00:00.000000000' '2014-12-31T12:00:00.000000000'
#  '2014-12-31T18:00:00.000000000']

# concat and sort time
x2 = xr.concat([x, empty], "time").sortby("time")

# after insertion
print(x2.time[-5:].values)

# ['2014-12-31T00:00:00.000000000' '2014-12-31T06:00:00.000000000'
#  '2014-12-31T07:00:00.000000000' '2014-12-31T12:00:00.000000000'
#  '2014-12-31T18:00:00.000000000']

該示例運行良好,但我不確定這是否是最好的(甚至是正確的)方法。

我擔心的是將其用於更大的數據集,特別是與 dask-array 支持的數據集。

有沒有更好的方法來填充缺失的二維數組? 插入到 dask 支持的數據集中時,使用 dask 支持的“填充數組”會更好嗎?

為此,您可能會考慮使用帶有常量fill_value的 xarray 的reindex方法:

import numpy as np
import xarray as xr

x = xr.tutorial.load_dataset("air_temperature")
missing_time = np.datetime64("2014-12-31T07:00:00")
missing_time_da = xr.DataArray([missing_time], dims=["time"], coords=[[missing_time]])
full_time = xr.concat([x.time, missing_time_da], dim="time")
full = x.reindex(time=full_time, fill_value=-3000.0).sortby("time")

我認為你的方法和reindex方法都會自動使用 dask-backed arrays 如果x是 dask-backed。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM