Question

Using Polars with Python and being thrown the following exception: AttributeError: 'Expr' object has no attribute 'apply'

I am trying to apply a function to a Dataframe column (series) that retrieves the day of the week based on the timestamps in the column. However, I am being thrown the following exception, even though the Polars docs include documentation for polars.Expr.apply.

AttributeError: 'Expr' object has no attribute 'apply'.

My goal is to create a new column of day names using the following code where the alertTime column is of dtype datetime64:

def get_day(dt_obj):
    days_of_week = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
    return days_of_week[dt_obj.weekday()]
    
# Get the day of the week from the timestamp
df = df.with_columns(
  pl.col('alertTime').apply(get_day, return_dtype=pl.Utf8).alias('day_of_week')
)

Could anyone help with where I might be going wrong?

 3  338  3
1 Jan 1970

Solution

 1

apply was renamed to .map_elements() some time ago.

Previous versions printed a deprecation warning, but it was eventually removed after a grace period.

You're likely looking at the docs for an older version of Polars, but there is a "version switcher" on the docs site:

As for the actual task, you can also do it natively using .dt.to_string()

import datetime
import polars as pl

pl.select(
   pl.lit(str(datetime.datetime.now()))
     .str.to_datetime()
     .dt.to_string("%A")
)      
shape: (1, 1)
┌─────────┐
│ literal │
│ ---     │
│ str     │
╞═════════╡
│ Tuesday │
└─────────┘
2024-07-16
jqurious