Я хочу синхронизировать два числовых массива меток времени друг с другом с помощью Polars LazyFrames.
Предположим, что у меня есть два числовых массива меток времени, которые хранятся с помощью LazyFrames:
Код: Выделить всё
import polars as pl
timestamps = pl.LazyFrame(
np.array(
[
np.datetime64("1970-01-01T00:00:00.500000000"),
np.datetime64("1970-01-01T00:00:01.500000000"),
np.datetime64("1970-01-01T00:00:02.600000000"),
np.datetime64("1970-01-01T00:00:03.400000000"),
np.datetime64("1970-01-01T00:00:04.500000000"),
np.datetime64("1970-01-01T00:00:05.300000000"),
np.datetime64("1970-01-01T00:00:06.200000000"),
np.datetime64("1970-01-01T00:00:07.400000000"),
np.datetime64("1970-01-01T00:00:08.500000000"),
]
),
schema={"values": pl.Datetime}
)
other_timestamps = pl.LazyFrame(
np.array(
[
np.datetime64("1970-01-01T00:00:01.500000000"),
np.datetime64("1970-01-01T00:00:02.000000000"),
np.datetime64("1970-01-01T00:00:02.500000000"),
np.datetime64("1970-01-01T00:00:04.500000000"),
np.datetime64("1970-01-01T00:00:06.000000000"),
np.datetime64("1970-01-01T00:00:06.500000000"),
]
),
schema={"values": pl.Datetime}
)
Код: Выделить всё
import numpy as np
import numpy.typing as npt
def _np_sync_to(
timestamps: npt.ArrayLike[np.datetime64],
other: npt.ArrayLike[np.datetime64],
tolerance: str,
):
outer_diffs = np.abs(np.subtract.outer(other, timestamps))
closest_timestamps_indices = outer_diffs.argmin(0)
closest_timestamps = other[closest_timestamps_indices]
diffs = np.abs(closest_timestamps - timestamps)
tolerance = parse_timedelta(tolerance)
within_tolerance = diffs
Я пытался реализовать это эквивалентно с помощью Polars, но размеры внешнего вычитания неверны, и я думаю, что в целом есть лучший способ выполнить вычисления:
[code]# inspired by https://stackoverflow.com/questions/77748729/polars-equivalent-to-np-outer
def sync_to(timestamps, other, tolerance: str):
def _outer(
a: pl.DataFrame | pl.LazyFrame, b: pl.DataFrame | pl.LazyFrame
):
# I guess the following line is incorrect
nrows = pl.len().sqrt().cast(pl.Int32)
return (
a.select("values")
.join(b.select("values"), how="cross")
.select(
computed=(pl.col("values") - pl.col("values_right")).abs()
)
.group_by(pl.arange(0, pl.len()) // nrows, maintain_order=True)
.agg("computed")
.select(pl.col("computed").list.to_struct())
.unnest("computed")
)
outer_diffs = timestamps.pipe(_outer, other)
Код: Выделить всё
ts1 = timestamps.sort("values").join_asof(
other.sort("values"),
on="values",
strategy="nearest",
tolerance=tolerance,
)
Источник: https://stackoverflow.com/questions/781 ... evaluation