mirror of
https://github.com/nushell/nushell.git
synced 2026-12-02 18:24:08 +08:00
Lazy and expression support for polars rolling (#18730)
## Description Implemented lazyframe and expression support for `polars rolling`. I also made some minor changes to make typing more strict around taking NuLazyGroupBy explicitly as output and inputs. ## User-facing changes (Release notes) - `polars rolling` can now be used natively with lazy frames and be used in expressions.
This commit is contained in:
@@ -41,6 +41,10 @@ impl PluginCommand for LazyAggregate {
|
||||
PolarsPluginType::NuLazyFrame.into(),
|
||||
PolarsPluginType::NuLazyFrame.into(),
|
||||
),
|
||||
(
|
||||
PolarsPluginType::NuLazyGroupBy.into(),
|
||||
PolarsPluginType::NuLazyFrame.into(),
|
||||
),
|
||||
])
|
||||
.category(Category::Custom("lazyframe".into()))
|
||||
}
|
||||
|
||||
@@ -37,11 +37,11 @@ impl PluginCommand for ToLazyGroupBy {
|
||||
.input_output_types(vec![
|
||||
(
|
||||
PolarsPluginType::NuDataFrame.into(),
|
||||
PolarsPluginType::NuDataFrame.into(),
|
||||
PolarsPluginType::NuLazyGroupBy.into(),
|
||||
),
|
||||
(
|
||||
PolarsPluginType::NuLazyFrame.into(),
|
||||
PolarsPluginType::NuLazyFrame.into(),
|
||||
PolarsPluginType::NuLazyGroupBy.into(),
|
||||
),
|
||||
])
|
||||
.category(Category::Custom("lazyframe".into()))
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
use crate::values::{Column, NuDataFrame, PolarsPluginType};
|
||||
use crate::values::conversion::convert_duration;
|
||||
use crate::values::{
|
||||
Column, NuDataFrame, NuExpression, NuLazyFrame, NuLazyGroupBy, PolarsPluginObject,
|
||||
PolarsPluginType, cant_convert_err,
|
||||
};
|
||||
use crate::{PolarsPlugin, values::CustomValueSupport};
|
||||
|
||||
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
|
||||
@@ -7,6 +11,8 @@ use nu_protocol::{
|
||||
SyntaxShape, Value, shell_error::generic::GenericError,
|
||||
};
|
||||
use polars::prelude::{DataType, IntoSeries, RollingOptionsFixedWindow, SeriesOpsTime};
|
||||
use polars::time::{ClosedWindow, Duration as PolarsDuration, RollingGroupOptions};
|
||||
use polars_lazy::dsl::col;
|
||||
|
||||
enum RollType {
|
||||
Min,
|
||||
@@ -23,12 +29,8 @@ impl RollType {
|
||||
"sum" => Ok(Self::Sum),
|
||||
"mean" => Ok(Self::Mean),
|
||||
_ => Err(ShellError::Generic(
|
||||
GenericError::new(
|
||||
"Wrong operation",
|
||||
"Operation not valid for cumulative",
|
||||
span,
|
||||
)
|
||||
.with_help("Allowed values: min, max, sum, mean"),
|
||||
GenericError::new("Wrong operation", "Operation not valid for rolling", span)
|
||||
.with_help("Allowed values: min, max, sum, mean"),
|
||||
)),
|
||||
}
|
||||
}
|
||||
@@ -54,21 +56,63 @@ impl PluginCommand for Rolling {
|
||||
}
|
||||
|
||||
fn description(&self) -> &str {
|
||||
"Rolling calculation for a series."
|
||||
"Rolling calculation for a series or expression, or a rolling group-by for a lazyframe."
|
||||
}
|
||||
|
||||
fn signature(&self) -> Signature {
|
||||
Signature::build(self.name())
|
||||
.required("type", SyntaxShape::String, "Rolling operation.")
|
||||
.required("window", SyntaxShape::Int, "Window size for rolling.")
|
||||
.optional(
|
||||
"type",
|
||||
SyntaxShape::String,
|
||||
"Rolling operation (min, max, sum, mean). Required for dataframe and expression inputs.",
|
||||
)
|
||||
.optional(
|
||||
"window",
|
||||
SyntaxShape::Int,
|
||||
"Window size for rolling. Required for dataframe and expression inputs.",
|
||||
)
|
||||
.named(
|
||||
"index-column",
|
||||
SyntaxShape::String,
|
||||
"Time or index column to roll over. Required for lazyframe input.",
|
||||
Some('i'),
|
||||
)
|
||||
.named(
|
||||
"period",
|
||||
SyntaxShape::OneOf(vec![SyntaxShape::Duration, SyntaxShape::String, SyntaxShape::Int]),
|
||||
"Rolling window width (e.g. 7day, \"7d\", 1wk, \"1mo\", \"2i\", ). Required for lazyframe input.",
|
||||
Some('p'),
|
||||
)
|
||||
.named(
|
||||
"offset",
|
||||
SyntaxShape::OneOf(vec![SyntaxShape::Duration, SyntaxShape::String, SyntaxShape::Int]),
|
||||
"Offset of the rolling window relative to the index column (default: 1ns).",
|
||||
Some('o'),
|
||||
)
|
||||
.named(
|
||||
"closed",
|
||||
SyntaxShape::String,
|
||||
"Which boundary of the window is closed: left, right, both, none (default: left).",
|
||||
Some('c'),
|
||||
)
|
||||
.named(
|
||||
"group-by",
|
||||
SyntaxShape::List(Box::new(SyntaxShape::Any)),
|
||||
"Additional expressions to group by within each rolling window.",
|
||||
Some('g'),
|
||||
)
|
||||
.input_output_types(vec![
|
||||
(
|
||||
PolarsPluginType::NuDataFrame.into(),
|
||||
PolarsPluginType::NuDataFrame.into(),
|
||||
),
|
||||
(
|
||||
PolarsPluginType::NuExpression.into(),
|
||||
PolarsPluginType::NuExpression.into(),
|
||||
),
|
||||
(
|
||||
PolarsPluginType::NuLazyFrame.into(),
|
||||
PolarsPluginType::NuLazyFrame.into(),
|
||||
PolarsPluginType::NuLazyGroupBy.into(),
|
||||
),
|
||||
])
|
||||
.category(Category::Custom("dataframe".into()))
|
||||
@@ -118,6 +162,72 @@ impl PluginCommand for Rolling {
|
||||
.into_value(Span::test_data()),
|
||||
),
|
||||
},
|
||||
Example {
|
||||
description: "Rolling sum for an expression in a lazyframe",
|
||||
example: "[[a]; [1] [2] [3] [4] [5]]
|
||||
| polars into-df
|
||||
| polars select (polars col a | polars rolling sum 2 | polars as roll_a)
|
||||
| polars collect
|
||||
| polars drop-nulls
|
||||
| polars collect",
|
||||
result: Some(
|
||||
NuDataFrame::try_from_columns(
|
||||
vec![Column::new(
|
||||
"roll_a".to_string(),
|
||||
vec![
|
||||
Value::test_int(3),
|
||||
Value::test_int(5),
|
||||
Value::test_int(7),
|
||||
Value::test_int(9),
|
||||
],
|
||||
)],
|
||||
None,
|
||||
Span::test_data(),
|
||||
)
|
||||
.expect("simple df for test should not fail")
|
||||
.into_value(Span::test_data()),
|
||||
),
|
||||
},
|
||||
Example {
|
||||
description: "Rolling sum over a 2-row integer window on a lazyframe",
|
||||
example: r#"[[idx val]; [1 10] [2 20] [3 30] [4 40] [5 50]]
|
||||
| polars into-lazy
|
||||
| polars rolling --index-column idx --period 2i
|
||||
| polars agg [(polars col val | polars sum | polars as val_sum)]
|
||||
| polars collect
|
||||
| polars sort-by idx
|
||||
| polars collect"#,
|
||||
result: Some(
|
||||
NuDataFrame::try_from_columns(
|
||||
vec![
|
||||
Column::new(
|
||||
"idx".to_string(),
|
||||
vec![
|
||||
Value::test_int(1),
|
||||
Value::test_int(2),
|
||||
Value::test_int(3),
|
||||
Value::test_int(4),
|
||||
Value::test_int(5),
|
||||
],
|
||||
),
|
||||
Column::new(
|
||||
"val_sum".to_string(),
|
||||
vec![
|
||||
Value::test_int(50),
|
||||
Value::test_int(70),
|
||||
Value::test_int(90),
|
||||
Value::test_int(50),
|
||||
Value::test_int(0),
|
||||
],
|
||||
),
|
||||
],
|
||||
None,
|
||||
Span::test_data(),
|
||||
)
|
||||
.expect("simple df for test should not fail")
|
||||
.into_value(Span::test_data()),
|
||||
),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
@@ -129,22 +239,135 @@ impl PluginCommand for Rolling {
|
||||
mut input: PipelineData,
|
||||
) -> Result<PipelineData, LabeledError> {
|
||||
let metadata = input.take_metadata();
|
||||
command(plugin, engine, call, input)
|
||||
.map_err(LabeledError::from)
|
||||
.map(|pd| pd.set_metadata(metadata))
|
||||
let value = input.into_value(call.head)?;
|
||||
|
||||
match PolarsPluginObject::try_from_value(plugin, &value)? {
|
||||
PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy),
|
||||
other => {
|
||||
let roll_type: Spanned<String> = call.req(0)?;
|
||||
let roll_type = RollType::from_str(&roll_type.item, roll_type.span)
|
||||
.map_err(LabeledError::from)?;
|
||||
match other {
|
||||
PolarsPluginObject::NuDataFrame(df) => {
|
||||
command_eager(plugin, engine, call, roll_type, df)
|
||||
}
|
||||
PolarsPluginObject::NuExpression(expr) => {
|
||||
command_expr(plugin, engine, call, roll_type, expr)
|
||||
}
|
||||
_ => Err(cant_convert_err(
|
||||
&value,
|
||||
&[
|
||||
PolarsPluginType::NuDataFrame,
|
||||
PolarsPluginType::NuLazyFrame,
|
||||
PolarsPluginType::NuExpression,
|
||||
],
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
.map_err(LabeledError::from)
|
||||
.map(|pd| pd.set_metadata(metadata))
|
||||
}
|
||||
}
|
||||
|
||||
fn command(
|
||||
fn command_lazy(
|
||||
plugin: &PolarsPlugin,
|
||||
engine: &EngineInterface,
|
||||
call: &EvaluatedCall,
|
||||
input: PipelineData,
|
||||
mut lazy: NuLazyFrame,
|
||||
) -> Result<PipelineData, ShellError> {
|
||||
let index_column: String = call.get_flag("index-column")?.ok_or_else(|| {
|
||||
ShellError::Generic(GenericError::new(
|
||||
"Missing required flag",
|
||||
"--index-column is required for lazyframe input",
|
||||
call.head,
|
||||
))
|
||||
})?;
|
||||
|
||||
let period: PolarsDuration = call
|
||||
.get_flag("period")?
|
||||
.map(convert_duration)
|
||||
.transpose()?
|
||||
.unwrap_or_else(|| PolarsDuration::new(1));
|
||||
|
||||
let offset: PolarsDuration = call
|
||||
.get_flag("offset")?
|
||||
.map(convert_duration)
|
||||
.transpose()?
|
||||
.unwrap_or_else(|| PolarsDuration::new(1));
|
||||
|
||||
let closed_window = match call.get_flag_value("closed") {
|
||||
Some(Value::String { val, .. }) => match val.as_str() {
|
||||
"left" => ClosedWindow::Left,
|
||||
"right" => ClosedWindow::Right,
|
||||
"both" => ClosedWindow::Both,
|
||||
"none" => ClosedWindow::None,
|
||||
other => {
|
||||
return Err(ShellError::Generic(GenericError::new(
|
||||
"Invalid closed window value",
|
||||
format!("Got '{other}', expected one of: left, right, both, none"),
|
||||
call.head,
|
||||
)));
|
||||
}
|
||||
},
|
||||
_ => ClosedWindow::Left,
|
||||
};
|
||||
|
||||
let group_by_exprs = match call.get_flag_value("group-by") {
|
||||
Some(list) => NuExpression::extract_exprs(plugin, list)?,
|
||||
None => vec![],
|
||||
};
|
||||
|
||||
let options = RollingGroupOptions {
|
||||
index_column: index_column.as_str().into(),
|
||||
period,
|
||||
offset,
|
||||
closed_window,
|
||||
};
|
||||
|
||||
let schema = lazy.schema().clone()?;
|
||||
let from_eager = lazy.from_eager;
|
||||
let group_by = lazy
|
||||
.to_polars()
|
||||
.rolling(col(index_column.as_str()), group_by_exprs, options);
|
||||
NuLazyGroupBy::new(group_by, from_eager, schema).to_pipeline_data(plugin, engine, call.head)
|
||||
}
|
||||
|
||||
fn command_expr(
|
||||
plugin: &PolarsPlugin,
|
||||
engine: &EngineInterface,
|
||||
call: &EvaluatedCall,
|
||||
roll_type: RollType,
|
||||
expr: NuExpression,
|
||||
) -> Result<PipelineData, ShellError> {
|
||||
let window_size: usize = call.req(1)?;
|
||||
let rolling_opts = RollingOptionsFixedWindow {
|
||||
window_size,
|
||||
min_periods: window_size,
|
||||
..RollingOptionsFixedWindow::default()
|
||||
};
|
||||
|
||||
let polars_expr = expr.into_polars();
|
||||
let res: NuExpression = match roll_type {
|
||||
RollType::Max => polars_expr.rolling_max(rolling_opts),
|
||||
RollType::Min => polars_expr.rolling_min(rolling_opts),
|
||||
RollType::Sum => polars_expr.rolling_sum(rolling_opts),
|
||||
RollType::Mean => polars_expr.rolling_mean(rolling_opts),
|
||||
}
|
||||
.into();
|
||||
|
||||
res.to_pipeline_data(plugin, engine, call.head)
|
||||
}
|
||||
|
||||
fn command_eager(
|
||||
plugin: &PolarsPlugin,
|
||||
engine: &EngineInterface,
|
||||
call: &EvaluatedCall,
|
||||
roll_type: RollType,
|
||||
df: NuDataFrame,
|
||||
) -> Result<PipelineData, ShellError> {
|
||||
let roll_type: Spanned<String> = call.req(0)?;
|
||||
let window_size: usize = call.req(1)?;
|
||||
|
||||
let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?;
|
||||
let series = df.as_series(call.head)?;
|
||||
|
||||
if let DataType::Object(..) = series.dtype() {
|
||||
@@ -155,8 +378,6 @@ fn command(
|
||||
)));
|
||||
}
|
||||
|
||||
let roll_type = RollType::from_str(&roll_type.item, roll_type.span)?;
|
||||
|
||||
let rolling_opts = RollingOptionsFixedWindow {
|
||||
window_size,
|
||||
min_periods: window_size,
|
||||
|
||||
@@ -51,6 +51,10 @@ impl PluginCommand for FirstDF {
|
||||
PolarsPluginType::NuLazyFrame.into(),
|
||||
PolarsPluginType::NuLazyFrame.into(),
|
||||
),
|
||||
(
|
||||
PolarsPluginType::NuLazyGroupBy.into(),
|
||||
PolarsPluginType::NuLazyFrame.into(),
|
||||
),
|
||||
])
|
||||
.category(Category::Custom("dataframe".into()))
|
||||
}
|
||||
|
||||
@@ -49,6 +49,10 @@ impl PluginCommand for LastDF {
|
||||
PolarsPluginType::NuLazyFrame.into(),
|
||||
PolarsPluginType::NuLazyFrame.into(),
|
||||
),
|
||||
(
|
||||
PolarsPluginType::NuLazyGroupBy.into(),
|
||||
PolarsPluginType::NuLazyFrame.into(),
|
||||
),
|
||||
])
|
||||
.category(Category::Custom("dataframe".into()))
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ use std::{cmp::Ordering, fmt};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub use file_type::PolarsFileType;
|
||||
pub use nu_dataframe::{Axis, Column, NuDataFrame, NuDataFrameCustomValue};
|
||||
pub use nu_dataframe::{Axis, Column, NuDataFrame, NuDataFrameCustomValue, conversion};
|
||||
pub use nu_dtype::NuDataType;
|
||||
pub use nu_dtype::{datatype_list, str_to_dtype, str_to_time_unit};
|
||||
pub use nu_expression::{NuExpression, NuExpressionCustomValue};
|
||||
|
||||
@@ -20,6 +20,7 @@ use polars::prelude::{
|
||||
|
||||
use nu_protocol::shell_error::generic::GenericError;
|
||||
use nu_protocol::{Record, ShellError, Span, Value};
|
||||
use polars::time::Duration as PolarsDuration;
|
||||
use polars_arrow::Either;
|
||||
use polars_arrow::array::Utf8ViewArray;
|
||||
|
||||
@@ -1551,6 +1552,27 @@ fn utf8_view_array_to_value(array: &Utf8ViewArray, span: Span) -> Vec<Value> {
|
||||
.collect::<Vec<Value>>()
|
||||
}
|
||||
|
||||
pub fn convert_duration(v: Value) -> Result<PolarsDuration, ShellError> {
|
||||
match v {
|
||||
Value::Duration { val, .. } => Ok(PolarsDuration::new(val)),
|
||||
Value::Int { val, .. } => Ok(PolarsDuration::new(val)),
|
||||
Value::String { ref val, .. } => {
|
||||
PolarsDuration::try_parse(val).map_err(|e| ShellError::CantConvert {
|
||||
to_type: "duration".into(),
|
||||
from_type: "string".into(),
|
||||
span: v.span(),
|
||||
help: Some(format!("Could not parse string as duration: {e}")),
|
||||
})
|
||||
}
|
||||
_ => Err(ShellError::CantConvert {
|
||||
to_type: "duration".into(),
|
||||
from_type: v.get_type().to_string(),
|
||||
span: v.span(),
|
||||
help: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use indexmap::indexmap;
|
||||
@@ -1983,4 +2005,22 @@ mod tests {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_convert_duration() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let span = Span::test_data();
|
||||
let duration_value = Value::duration(1_000_000, span);
|
||||
let converted_duration = convert_duration(duration_value.clone())?;
|
||||
assert_eq!(converted_duration, PolarsDuration::new(1_000_000));
|
||||
|
||||
let int_value = Value::int(1_000_000, span);
|
||||
let converted_int_duration = convert_duration(int_value.clone())?;
|
||||
assert_eq!(converted_int_duration, PolarsDuration::new(1_000_000));
|
||||
|
||||
let invalid_value = Value::string("invalid".to_string(), span);
|
||||
let result = convert_duration(invalid_value.clone());
|
||||
assert!(result.is_err());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
mod between_values;
|
||||
mod conversion;
|
||||
pub mod conversion;
|
||||
mod custom_value;
|
||||
mod operations;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user