我想测试两个 Polars DataFame 对象是否等效,其中包含代表日期的列。
如果我使用标准库中的
datetime.date
,我不会有任何问题:
import datetime as dt
import polars as pl
from polars.testing import assert_frame_equal
assert_frame_equal(pl.DataFrame({"foo": [1], "bar": [dt.date(2000, 1, 1)]}), pl.DataFrame({"foo": [1], "bar": [dt.date(2000, 1, 1)]}))
但是,如果我尝试使用极坐标中的
Date
类型,比较就会失败,但 PanicException: not implemented
例外。
assert_frame_equal(pl.DataFrame({"foo": [1], "bar": [pl.Date(2000, 1, 1)]}), pl.DataFrame({"foo": [1], "bar": [pl.Date(2000, 1, 1)]}))
有没有办法在
Date
中使用极坐标 DataFrame
类型并且仍然能够比较两个对象?
我认为你不应该像那样使用
pl.Date
,否则你的DataFrame
是dtype object
,这可能不是你想要的:
In [2]: pl.DataFrame({"foo": [1], "bar": [pl.Date(2000, 1, 1)]})
Out[2]:
shape: (1, 2)
┌─────┬─────────────────────────────────────┐
│ foo ┆ bar │
│ --- ┆ --- │
│ i64 ┆ object │
╞═════╪═════════════════════════════════════╡
│ 1 ┆ <polars.datatypes.Date object at... │
└─────┴─────────────────────────────────────┘
相反,请执行以下操作:
df1 = pl.DataFrame({"foo": [1], "bar": ['2000-01-01']}).with_columns(pl.col('bar').str.to_date())
df2 = pl.DataFrame({"foo": [1], "bar": ['2000-01-01']}).with_columns(pl.col('bar').str.to_date())
assert_frame_equal(df1, df2)
这很好用
您不应将
pl.Date
放入 DataFrame
中。
pl.Date
是一个 dtype
对象,不应用于实例化值。 DataFrame
的列类型也表明 Polars 不知道如何处理它,因为它将其推断为 object
dtype(阅读,我不知道你给了我什么)。
使用Python原生的
datetime, date, time, timedelta
是正确的选择。
import polars as pl
from polars.testing import assert_frame_equal
from datetime import date
assert_frame_equal(pl.DataFrame({"foo": [1], "bar": [date(2000, 1, 1)]}),
pl.DataFrame({"foo": [1], "bar": [date(2000, 1, 1)]}))