0

我正在尝试借助分类功能和惰性 API 加入两个数据框。我尝试按照用户指南中描述的方式进行操作(https://pola-rs.github.io/polars-book/user-guide/performance/strings.html

count = admin_df.groupby(['admin','EVENT_DATE']).pivot(pivot_column='FIVE_TYPE',values_column='count').first().lazy()
fatalities = admin_df.groupby(['admin','EVENT_DATE']).pivot(pivot_column='FIVE_TYPE',values_column='FATALITIES').first().lazy()
fatalities = fatalities.with_column(pl.col("admin").cast(pl.Categorical))
count = count.with_column(pl.col("admin").cast(pl.Categorical))
admin_df = fatalities.join(count,on=['admin','EVENT_DATE']).collect()

但我收到以下错误:

    Traceback (most recent call last):
  File "country_level.py", line 33, in <module>
    country_level('/c/Users/Sebastian/feast/fluent_sunfish/data/ACLED_geocoded.parquet')
  File "country_level.py", line 10, in country_level
    country_df=aggregate_by_date(df)
  File "country_level.py", line 29, in aggregate_by_date
    admin_df = fatalities.join(count,on=['admin','EVENT_DATE']).collect()
  File "/home/sebastian/.local/lib/python3.8/site-packages/polars/internals/lazy_frame.py", line 293, in collect
    return pli.wrap_df(ldf.collect())
RuntimeError: Any(ValueError("joins on categorical dtypes can only happen if they are created under the same global string cache"))

使用with pl.StringCache():一切正常,尽管用户指南说如果您使用惰性 API,则不需要它,我是否遗漏了什么或者这是一个错误?

4

1 回答 1

1

用户指南不正确。您需要设置全局字符串缓存。

pl.StringCache():您可以使用或设置全局字符串缓存pl.Config.set_global_string_cache


import polars as pl
pl.Config.set_global_string_cache()

lf1 = pl.DataFrame({
    "a": ["foo", "bar", "ham"], 
    "b": [1, 2, 3]
}).lazy()
lf2 = pl.DataFrame({
    "a": ["foo", "spam", "eggs"], 
    "c": [3, 2, 2]
}).lazy()

lf1 = lf1.with_column(pl.col("a").cast(pl.Categorical))
lf2 = lf2.with_column(pl.col("a").cast(pl.Categorical))

lf1.join(df2, on="a", how="inner").collect()

输出:

shape: (1, 3)
┌───────┬─────┬─────┐
│ a     ┆ b   ┆ c   │
│ ---   ┆ --- ┆ --- │
│ cat   ┆ i64 ┆ i64 │
╞═══════╪═════╪═════╡
│ "foo" ┆ 1   ┆ 3   │
└───────┴─────┴─────┘

于 2021-12-05T15:45:52.143 回答