如何在极坐标中创建附加列“weekofyear”、“month”和“dayofweek”?

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

我正在尝试根据极坐标中的现有列名称创建其他列。 现有列名称是 starttime。此列包含日期时间。

开始时间 结束时间 存储ID 卷_id avgiops
2022-02-10 09:32:20 2022-02-10 09:34:28 TUNYKYPG72 4c8d6c31 27
2022-02-10 10:34:10 2022-02-10 10:35:12 TUNYKYPG42 4c8d6d31 34

从这个表中,我想创建其他列,例如 weekofyear、dayofweek、year 等。

pl_df.with_column(pl.col('starttime').str.strptime(pl.Date, fmt='%Y').cast(pl.Datetime)).alias
("year")

但它失败了

exceptions.ComputeError:严格转换为日期失败,可能已设置 严格=假

在pyspark中,我们可以像下面这样创建它

df_dates = pl.select(
        [
            weekofyear("starttime").alias("week"),
            dayofweek("starttime").alias("weekday"),
            hour("starttime").alias("hour"),
            dayofmonth("starttime").alias("day"),
            to_date("starttime").alias("collectiontime"),
            starttime,endtime,storageid,volume_id,avgiops])

如何在极坐标中创建附加列 weekofyear、dayofweek、month?

dataframe python-polars
1个回答
3
投票

第一步是将字符串转换为 Datetime 对象,即

.str.to_datetime()

您可以使用Temporal命名空间中的方法来提取您想要的信息。

df.with_columns(
   pl.col("starttime").str.to_datetime()
).with_columns(
   pl.col("starttime").dt.week().alias("week"),
   pl.col("starttime").dt.weekday().alias("weekday"),
   pl.col("starttime").dt.hour().alias("hour"),
   pl.col("starttime").dt.day().alias("day")
)
shape: (2, 9)
┌─────────────────────┬─────────────────────┬────────────┬───────────┬─────────┬──────┬─────────┬──────┬─────┐
│ starttime           ┆ endtime             ┆ storageid  ┆ volume_id ┆ avgiops ┆ week ┆ weekday ┆ hour ┆ day │
│ ---                 ┆ ---                 ┆ ---        ┆ ---       ┆ ---     ┆ ---  ┆ ---     ┆ ---  ┆ --- │
│ datetime[μs]        ┆ str                 ┆ str        ┆ str       ┆ i64     ┆ i8   ┆ i8      ┆ i8   ┆ i8  │
╞═════════════════════╪═════════════════════╪════════════╪═══════════╪═════════╪══════╪═════════╪══════╪═════╡
│ 2022-02-10 09:32:20 ┆ 2022-02-10 09:34:28 ┆ TUNYKYPG72 ┆ 4c8d6c31  ┆ 27      ┆ 6    ┆ 4       ┆ 9    ┆ 10  │
│ 2022-02-10 10:34:10 ┆ 2022-02-10 10:35:12 ┆ TUNYKYPG42 ┆ 4c8d6d31  ┆ 34      ┆ 6    ┆ 4       ┆ 10   ┆ 10  │
└─────────────────────┴─────────────────────┴────────────┴───────────┴─────────┴──────┴─────────┴──────┴─────┘
© www.soinside.com 2019 - 2024. All rights reserved.