Ask Your Question
2

How can a date column be created using the year, month and day data in a Polars dataframe?

asked 2023-05-24 11:28:03 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-24 11:57:02 +0000

scrum gravatar image

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 |
+------+------+-----+------------+
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-24 11:28:03 +0000

Seen: 18 times

Last updated: May 24 '23