我正在尝试将一个函数应用于 Dataframe 列(系列),该函数根据列中的时间戳检索星期几。但是,即使 Polars 文档包含“polars.Expr.apply”的文档,我也会抛出以下异常:AttributeError:“Expr”对象没有属性“apply”。
我的目标是使用以下代码创建一个新的日期名称列,其中“alertTime”列的数据类型为 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')
)
任何人都可以帮助解决我可能出错的地方吗?
您可能正在查看旧版本 Polars 的文档,
apply
已重命名为 .map_elements()
.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 │
└─────────┘