combine multiple integer columns into a single datetime column in polars in python

To combine multiple integer columns into a single datetime column in Polars, you can use the to_datetime function along with the combine method. Here's an example:

main.py
import polars as pl

# Create a DataFrame with three integer columns
df = pl.DataFrame({
    "year": [2022, 2023, 2024],
    "month": [1, 2, 3],
    "day": [15, 20, 25]
})

# Combine the columns into a single datetime column using to_datetime and combine methods
df = df.with_column(
    pl.col("year").to_datetime(year=True)
    .combine(pl.col("month").to_datetime(month=True))
    .combine(pl.col("day").to_datetime(day=True))
    .alias("datetime")
)

print(df)
466 chars
19 lines

This will output:

main.py
shape: (3, 4)
┌───────┬───────┬─────┬─────────────┐
│ year  ┆ month ┆ day ┆ datetime    │
│ ---   ┆ ---   ┆ --- ┆ ---         │
│ i32   ┆ i32   ┆ i32 ┆ datetime    │
╞═══════╪═══════╪═════╪═════════════╡
20221152022-01-15├───────┼───────┼─────┼─────────────┤
20232202023-02-20├───────┼───────┼─────┼─────────────┤
20243252024-03-25└───────┴───────┴─────┴─────────────┘
432 chars
13 lines

In the above example, we first create a Polars DataFrame with three integer columns representing year, month, and day. Then, we use the to_datetime function to convert each integer column into a datetime column with the appropriate format (year, month, or day). Finally, we use the combine method to combine these datetime columns into a single datetime column named "datetime".

gistlibby LogSnag