如何在Python极坐标中添加持续时间到日期时间

问题描述 投票:0回答:1

我想在日期/时间中添加持续时间(以秒为单位)。我的数据看起来像

import polars as pl

df = pl.DataFrame(
    {
        "dt": [
            "2022-12-14T00:00:00", "2022-12-14T00:00:00", "2022-12-14T00:00:00",
        ],
        "seconds": [
            1.0, 2.2, 2.4,
        ],
    }
)

df = df.with_column(pl.col("dt").str.strptime(pl.Datetime).cast(pl.Datetime))

现在我天真的尝试是将浮点列转换为持续时间类型,以便能够将其添加到日期时间列(就像我在

pandas
中所做的那样)。

df = df.with_column(pl.col("seconds").cast(pl.Duration).alias("duration0"))

print(df.head())

┌─────────────────────┬─────────┬──────────────┐
│ dt                  ┆ seconds ┆ duration0    │
│ ---                 ┆ ---     ┆ ---          │
│ datetime[μs]        ┆ f64     ┆ duration[μs] │
╞═════════════════════╪═════════╪══════════════╡
│ 2022-12-14 00:00:00 ┆ 1.0     ┆ 0µs          │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2022-12-14 00:00:00 ┆ 2.2     ┆ 0µs          │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2022-12-14 00:00:00 ┆ 2.4     ┆ 0µs          │
└─────────────────────┴─────────┴──────────────┘

...给出了正确的数据类型,但是 值全部为零

我也尝试过

df = df.with_column(
    pl.col("seconds")
    .apply(lambda x: pl.duration(nanoseconds=x * 1e9))
    .alias("duration1")
)
print(df.head())
shape: (3, 4)
┌─────────────────────┬─────────┬──────────────┬─────────────────────────────────────┐
│ dt                  ┆ seconds ┆ duration0    ┆ duration1                           │
│ ---                 ┆ ---     ┆ ---          ┆ ---                                 │
│ datetime[μs]        ┆ f64     ┆ duration[μs] ┆ object                              │
╞═════════════════════╪═════════╪══════════════╪═════════════════════════════════════╡
│ 2022-12-14 00:00:00 ┆ 1.0     ┆ 0µs          ┆ 0i64.duration([0i64, 1000000000f... │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2022-12-14 00:00:00 ┆ 2.2     ┆ 0µs          ┆ 0i64.duration([0i64, 2200000000f... │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2022-12-14 00:00:00 ┆ 2.4     ┆ 0µs          ┆ 0i64.duration([0i64, 2400000000f... │
└─────────────────────┴─────────┴──────────────┴─────────────────────────────────────┘

它提供了一个对象类型列,这也没有帮助。 文档在该主题上有点稀疏,有更好的选择吗?

python datetime duration timedelta python-polars
1个回答
4
投票

更新: 值为零是一个 repr 格式问题 已通过此提交修复。

pl.duration()
可以这样使用:

df.with_columns(
   pl.col("dt").str.to_datetime()
   + pl.duration(nanoseconds=pl.col("seconds") * 1e9)
)
shape: (3, 2)
┌─────────────────────────┬─────────┐
│ dt                      ┆ seconds │
│ ---                     ┆ ---     │
│ datetime[μs]            ┆ f64     │
╞═════════════════════════╪═════════╡
│ 2022-12-14 00:00:01     ┆ 1.0     │
│ 2022-12-14 00:00:02.200 ┆ 2.2     │
│ 2022-12-14 00:00:02.400 ┆ 2.4     │
└─────────────────────────┴─────────┘
© www.soinside.com 2019 - 2024. All rights reserved.