在 Polars 中轻松将字符串列转换为 pl.datetime

Easily convert string column to pl.datetime in Polars

考虑一个 Polars 数据框,其中有一列 str 类型,以 '27 July 2020' 格式指示日期。我想将此列转换为 polars.datetime 类型,这与 Python 标准 datetime 不同。以下代码使用标准 datetime 格式,但 Polars 无法将列中的值识别为日期。

import polars as pl
from datetime import datetime

df = pd.read_csv('<some CSV file containing a column called 'event_date'>')
df = df.with_columns([   
        pl.col('event_date').apply(lambda x: x.replace(" ","-"))\
                            .apply(lambda x: datetime.strptime(x, '%d-%B-%Y'))
])

假设我们尝试进一步处理 df 以创建一个新列,指示事件发生在一年中的哪个季度。

df = df.with_columns([
        pl.col('event_date').apply(lambda x: x.month)\
                            .apply(lambda x: 1 if x in range(1,4) else 2 if x in range(4,7) else 3 if x in range(7,10) else 4)\
                            .alias('quarter')
])

代码 returns 出现以下错误,因为它将 event_type 限定为 dtype Object("object") 而不是 datetimepolars.datetime

thread '<unnamed>' panicked at 'dtype Object("object") not supported', src/series.rs:992:24
--- PyO3 is resuming a panic after fetching a PanicException from Python. ---
PanicException: Unwrapped panic from Python code

将字符串转换为 Date/Datetime 的最简单方法是使用 Polars 自己的 strptime 函数(而不是 Python 的 datetime模块)。

例如,让我们从这个数据开始。

import polars as pl

df = pl.DataFrame({
    'date_str': ["27 July 2020", "31 December 2020"]
})
print(df)
shape: (2, 1)
┌──────────────────┐
│ date_str         │
│ ---              │
│ str              │
╞══════════════════╡
│ 27 July 2020     │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 31 December 2020 │
└──────────────────┘

要转换,请使用 Polars 的 strptime 函数。

df.with_column(pl.col('date_str').str.strptime(pl.Date, fmt='%d %B %Y').cast(pl.Datetime))
shape: (2, 1)
┌─────────────────────┐
│ date_str            │
│ ---                 │
│ datetime[μs]        │
╞═════════════════════╡
│ 2020-07-27 00:00:00 │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2020-12-31 00:00:00 │
└─────────────────────┘

请注意,我们不需要用破折号替换空格。我已将结果转换为日期时间(根据您的问题),但您可以改用日期。

目前,apply方法在return类型为pythonDate/Datetime对象时不起作用,但有一个request用于此.也就是说,最好使用 Polars 的 strptime。它会比调用 python datetime 代码快得多。

编辑:从 Polars 0.13.19 开始,apply 方法会自动将 Python date/datetime 转换为 Polars Date/Datetime.