极坐标分类功能和惰性 API 无法按预期工作

问题描述 投票:0回答:1

我正在尝试借助分类功能和惰性 API 来连接两个 Dataframe。我尝试按照用户指南中描述的方式进行操作(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,则不需要它,我是否遗漏了某些内容,或者这是一个错误?

python python-polars
1个回答
7
投票

您可以使用

pl.StringCache():
pl.enable_string_cache()

设置全局字符串缓存
import polars as pl

pl.enable_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_columns(pl.col("a").cast(pl.Categorical))
lf2 = lf2.with_columns(pl.col("a").cast(pl.Categorical))

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

输出:

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

© www.soinside.com 2019 - 2024. All rights reserved.