Consider the following Polars dataframe:
import polars as pl
df = pl.DataFrame({'year': [2023], 'month': [2], 'day': [1]})
I want to construct a date column from year
, month
and day
. I know this can be done by first concatenating into a string and then parsing this:
df.with_column(
pl.concat_str([pl.col('year'), pl.col('month'), pl.col('day')], sep='-')
.str.strptime(pl.Date).alias('date')
)
But that seems like a detour. Is it possible to construct it directly with the three inputs? Something like this (that doesn't work):
import datetime
df.with_column(
datetime.date(pl.col('year'), pl.col('month'), pl.col('day')).alias('date')
)
polars has a pl.datetime
and pl.date
function that works the same as base datetime
except that it takes expressions so you can just do
df.with_columns(pl.date(pl.col('year'), pl.col('month'), pl.col('day')).alias('date'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.