I have a xarray.DataArray with a coordinate like
ary["time"] = [
"2000-01-01T03:04:05", # leading records are missing,
"2000-01-01T03:04:06",
"2000-01-01T03:04:08", # some medium records are missing,
"2000-01-01T03:04:09",
"2000-01-01T03:04:11",
...
"2000-01-01T06:54:02",
"2000-01-01T06:54:03" # and trailing records are missing.
]
and want to re-index to
ary["time"] = [
"2000-01-01T03:00:00",
"2000-01-01T03:00:01",
"2000-01-01T03:00:02",
...
"2000-01-01T03:04:06",
"2000-01-01T03:04:07",
"2000-01-01T03:04:08",
"2000-01-01T03:04:09",
...
"2000-01-01T06:59:57",
"2000-01-01T06:59:58",
"2000-01-01T06:59:59"
]
and set NaN at all missing records.
I found ary = ary.resample(time="1S").asfreq() but it only inserts medium records.
How can I indicate that left and right bounds are every hours? (or minutes or days?)
Sample (taken from gist):
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import xarray as xr
def make_ary():
time = []
for i in range(300, 14000):
if i % 3 != 2 and i % 5 != 2:
time.append(datetime(2000, 1, 1, 3, 0, 0) + timedelta(seconds=i))
data = np.random.rand(len(time))
return xr.DataArray(data=data, coords=[("time", time)], dims=["time"])
def make_expected():
expected = []
for i in range(0, 4*60*60):
expected.append(
datetime(2000, 1, 1, 3, 0, 0) + timedelta(seconds=i)
)
return pd.to_datetime(np.array(expected))
def make_not_expected():
'''
result of 'inserts medium records'
'''
not_expected = []
for i in range(300, 14000):
not_expected.append(
datetime(2000, 1, 1, 3, 0, 0) + timedelta(seconds=i)
)
return pd.to_datetime(np.array(not_expected))
def resample(ary):
return ary.resample(time="1S").asfreq()
def main():
ary = make_ary()
expected = make_expected()
not_expected = make_not_expected()
print(np.array_equal(ary["time"].values, expected)) # False
ary = resample(ary)
print(np.array_equal(ary["time"], expected)) # False
print(np.array_equal(ary["time"], not_expected)) # True, but not expected
main()