我有用 Rust/Polar 创建的数据框。 我需要一个脚本,允许我通过索引获取值并根据选择过滤另一个数据帧。
这是我的代码和数据结构:
这是 USER_INFO df:
┌───────────────────────┬──────────────┬────────────────┐
│ email ┆ user_role ┆ user_countries │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ list[str] │
╞═══════════════════════╪══════════════╪════════════════╡
│ [email protected] ┆ customer ┆ ["USA", "UK"]. │
从这个数据框中,我必须获得矢量格式的国家概率(注意我在 DF 中有超过 100 条记录)并过滤下面的 DF,让我们称之为 SHOPS_INFO:
┌─────────┬───────────────────────┬──────────────────┬──────────────┬──────────────┐
│ country ┆ partner ┆ resource ┆ amount ┆ item │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str ┆ str │
╞═════════╪═══════════════════════╪══════════════════╪══════════════╪══════════════╡
│ USA ┆ WALMART ┆ net ┆ one dollar ┆ Goveee │
这是我准备的代码:
// Take the countries of the first user in USER_INFO
let first_user_countries = USER_INFO
.column("user_countries")?
.get(0);
// apply the filter on a SHOPS_INFO
let filtered_df = SHOPS_INFO
.clone()
.lazy()
.filter(col("country").is_in(lit(&first_user_countries)))
.collect()?;
println!("{:?}", filtered_df);
它抛出错误
error[E0277]: the trait bound `&Result<polars::prelude::AnyValue<'_>, PolarsError>: polars::prelude::Literal` is not satisfied
--> src/main.rs:70:42
|
70 | .filter(col("country").is_in(lit(&first_user_countries)))
| --- ^^^^^^^^^^^^^^^^^^^^^ the trait `polars::prelude::Literal` is not implemented for `&Result<polars::prelude::AnyValue<'_>, PolarsError>`
但是如果我以静态方式定义国家/地区,代码就可以工作
// apply the filter on a SHOPS_INFO
let filtered_df = SHOPS_INFO
.clone()
.lazy()
.filter(col("country").is_in(lit(Series::new("".into(), ["USA"]))))
.collect()?;
println!("{:?}", filtered_df);
Result
和AnyValue
都没有实现所需的Literal
特质,但是从Series
中获得
PolarsResult<AnyValue>
实现它并不困难: let AnyValue::List(first_user_countries) = user_info.column("user_countries")?.get(0)? else {
polars_bail!(ShapeMismatch: "invalid datatype of column `user_countries`");
};
let filtered_df = shops_info
.lazy()
.filter(col("country").is_in(lit(first_user_countries)))
.collect()?;
仅针对拥有的
Series
实现,所以我也删除了借用,如果您需要保留它,则必须clone
它。