我需要通过在数据帧的日期时间列中搜索年份列表来过滤 Rust 中的极坐标数据帧。我试过了,但没用。
fn reduce_df(df: DataFrame, threshold: f64, years: &[i32]) -> Result<DataFrame, PolarsError> {
let years_vec = years.to_vec();
let mut df = df.lazy()
.filter(
col("time").dt().year()
.cast(DataType::Int64)
.is_in(years_vec)
)
.collect()?;
Ok(df)
}
出现此编译错误
error[E0599]: no method named `is_in` found for enum `Expr` in the current scope
--> src/main.rs:13:18
|
11 | / col("time").dt().year()
12 | | .cast(DataType::Int64)
13 | | .is_in(years_vec)
| |_________________-^^^^^
Claude 给出了以下内容,似乎可行,但太复杂了。
fn reduce_df(df: DataFrame, threshold: f64, years: &[i32]) -> Result<DataFrame, PolarsError> {
let years_vec = years.to_vec();
let mut df = df.lazy()
.filter(
col("time").dt().year()
.cast(DataType::Int64)
.apply(move |s| {
let s = s.i64()?;
Ok(Some(s.into_iter().map(|opt_v| {
opt_v.map(|v| years_vec.contains(&(v as i32)))
}).collect()))
}, GetOutput::from_type(DataType::Boolean))
)
.collect()?;
Ok(df)
}
is_in 有什么问题吗?
我是 Rust 新手,我不知道问题出在哪里。
实际上有两个与您当前的代码不相关的问题。
is_in
的原因很可能是您忘记激活 is_in
功能标志,如 is_in
功能文档中所述。因此,您的 Cargo.toml
应包含类似以下内容:polars = { version = "0.44.0", features= ["lazy", "is_in"] }
is_in
函数需要一个表达式作为函数参数,而不是Vec
。有多种方法可以解决此问题,我决定将切片转换为 Series
,然后使用 lit
函数来创建拟合表达式。在下面找到调整后的版本:
fn reduce_df(df: DataFrame, threshold: f64, years: &[i32]) -> Result<DataFrame, PolarsError> {
let years_series = Series::new("years".into(), years);
let mut df = df.lazy()
.filter(
col("time").dt().year()
.cast(DataType::Int64)
.is_in(lit(years_series))
)
.collect()?;
Ok(df)
}