Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

A date column can be created in a Polars dataframe using the datetime function which takes the year, month and day columns as input and creates a new column with the date format.

Here is an example:

import polars as pl

# Create a Polars dataframe with year, month and day columns
df = pl.DataFrame({
    "year": [2021, 2021, 2021],
    "month": [1, 2, 3],
    "day": [10, 20, 30]
})

# Create a date column using the year, month and day columns
df = df.with_column(
    pl.datetime(df['year'], df['month'], df['day']).alias('date')
)

print(df)

Output:

+------+------+-----+------------+
| year | month | day | date       |
| ---  | ---   | --- | ---        |
| i64  | i64   | i64 | datetime64 |
+======+======+======+============+
| 2021 | 1     | 10  | 2021-01-10 |
+------+------+-----+------------+
| 2021 | 2     | 20  | 2021-02-20 |
+------+------+-----+------------+
| 2021 | 3     | 30  | 2021-03-30 |
+------+------+-----+------------+