我有一个Python Polars 数据框,它非常大,Pandas 遇到内存错误。我想使用 python 极坐标,但遇到了一个问题,即采用日期的整数表示来创建两个新列:PeriodDate 和 LagDate。 我可以使用以下命令在 Pandas 的示例中执行此操作:
df['PeriodDate'] = pd.to_datetime(df['IntegerDate'],format='%Y%m')
df['LaggedDate'] = df['PeriodDate'] - pd.DateOffset(months=1)
我已尝试执行以下操作:
df.with_columns(
pl.col('IntegerDate').str.strptime(pl.Datetime,"%Y%m")
)
SchemaError: Series of dtype: Int64 != Utf8.
作为参考,“IntegerDate”列的格式为:202005、202006、...等
我还没有找到如何在极地做到这一点的好例子,所以任何帮助将不胜感激。
谢谢!
这是 Polars 的实现
import polars as pl
from datetime import datetime as dt
df = pl.DataFrame({'IntegerDate': [202005, 202006, 202207, 202303, 202109]})
df = df.with_columns(pl.col('IntegerDate').cast(pl.String).str.to_date('%Y%m').alias('PeriodDate'))
df
输出
┌─────────────┬────────────┐
│ IntegerDate ┆ PeriodDate │
│ --- ┆ --- │
│ i64 ┆ date │
╞═════════════╪════════════╡
│ 202005 ┆ 2020-05-01 │
│ 202006 ┆ 2020-06-01 │
│ 202207 ┆ 2022-07-01 │
│ 202303 ┆ 2023-03-01 │
│ 202109 ┆ 2021-09-01 │
└─────────────┴────────────┘
# add `LaggedDate`
df = df.with_columns(pl.col('PeriodDate').dt.offset_by('-1mo').alias('LaggedDate'))
df
最终输出
┌─────────────┬────────────┬────────────┐
│ IntegerDate ┆ PeriodDate ┆ LaggedDate │
│ --- ┆ --- ┆ --- │
│ i64 ┆ date ┆ date │
╞═════════════╪════════════╪════════════╡
│ 202005 ┆ 2020-05-01 ┆ 2020-04-01 │
│ 202006 ┆ 2020-06-01 ┆ 2020-05-01 │
│ 202207 ┆ 2022-07-01 ┆ 2022-06-01 │
│ 202303 ┆ 2023-03-01 ┆ 2023-02-01 │
│ 202109 ┆ 2021-09-01 ┆ 2021-08-01 │
└─────────────┴────────────┴────────────┘
.dt.offset_by()