考虑一个 Polars 数据框,其中一列是
假设我们尝试进一步处理
代码返回以下错误,因为它将
str
类型,表示日期格式为'27 July 2020'
。我想将这一列转换为polars.datetime
类型,该类型与Python标准库中的datetime
不同。下面的代码使用标准的datetime
格式可以工作,但是Polars不能将该列中的值识别为日期。import polars as pl
from datetime import datetime
df = pd.read_csv('<some CSV file containing a column called 'event_date'>')
df = df.with_columns([
pl.col('event_date').apply(lambda x: x.replace(" ","-"))\
.apply(lambda x: datetime.strptime(x, '%d-%B-%Y'))
])
假设我们尝试进一步处理
df
,以创建一个新列,指示事件发生的年度季度。df = df.with_columns([
pl.col('event_date').apply(lambda x: x.month)\
.apply(lambda x: 1 if x in range(1,4) else 2 if x in range(4,7) else 3 if x in range(7,10) else 4)\
.alias('quarter')
])
代码返回以下错误,因为它将
event_type
定义为 dtype Object("object")
而不是 datetime
或 polars.datetime
。thread '<unnamed>' panicked at 'dtype Object("object") not supported', src/series.rs:992:24
--- PyO3 is resuming a panic after fetching a PanicException from Python. ---
PanicException: Unwrapped panic from Python code
df = df.with_colu....
- PeJotafrom_repr
是纯粹的巫术,谢谢你提出这个问题! - Filippo Vitale