repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/index/set_with_idx.rs
crates/nu_plugin_polars/src/dataframe/command/index/set_with_idx.rs
use crate::{ PolarsPlugin, missing_flag_error, values::{CustomValueSupport, PolarsPluginType}, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::{ chunked_array::cast::CastOptions, prelude::{ChunkSet, DataType, IntoSeries}, }; #[derive(Clone)] pub struct SetWithIndex; impl PluginCommand for SetWithIndex { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars set-with-idx" } fn description(&self) -> &str { "Sets value in the given index." } fn signature(&self) -> Signature { Signature::build(self.name()) .required("value", SyntaxShape::Any, "value to be inserted in series") .required_named( "indices", SyntaxShape::Any, "list of indices indicating where to set the value", Some('i'), ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Set value in selected rows from series", example: r#"let series = ([4 1 5 2 4 3] | polars into-df); let indices = ([0 2] | polars into-df); $series | polars set-with-idx 6 --indices $indices"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_int(6), Value::test_int(1), Value::test_int(6), Value::test_int(2), Value::test_int(4), Value::test_int(3), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { command(plugin, engine, call, input).map_err(LabeledError::from) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let value: Value = call.req(0)?; let indices_value: Value = call .get_flag("indices")? .ok_or_else(|| missing_flag_error("indices", call.head))?; let indices_span = indices_value.span(); let indices = NuDataFrame::try_from_value_coerce(plugin, &indices_value, call.head)? .as_series(indices_span)?; let casted = match indices.dtype() { DataType::UInt32 | DataType::UInt64 | DataType::Int32 | DataType::Int64 => indices .as_ref() .cast(&DataType::UInt64, CastOptions::default()) .map_err(|e| ShellError::GenericError { error: "Error casting indices".into(), msg: e.to_string(), span: Some(indices_span), help: None, inner: vec![], }), _ => Err(ShellError::GenericError { error: "Incorrect type".into(), msg: "Series with incorrect type".into(), span: Some(indices_span), help: Some("Consider using a Series with type int type".into()), inner: vec![], }), }?; let indices = casted .u64() .map_err(|e| ShellError::GenericError { error: "Error casting indices".into(), msg: e.to_string(), span: Some(indices_span), help: None, inner: vec![], })? .into_iter() .flatten(); let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let series = df.as_series(call.head)?; let span = value.span(); let res = match value { Value::Int { val, .. } => { let chunked = series.i64().map_err(|e| ShellError::GenericError { error: "Error casting to i64".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], })?; let res = chunked.scatter_single(indices, Some(val)).map_err(|e| { ShellError::GenericError { error: "Error setting value".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], } })?; NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head) } Value::Float { val, .. } => { let chunked = series.f64().map_err(|e| ShellError::GenericError { error: "Error casting to f64".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], })?; let res = chunked.scatter_single(indices, Some(val)).map_err(|e| { ShellError::GenericError { error: "Error setting value".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], } })?; NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head) } Value::String { val, .. } => { let chunked = series.str().map_err(|e| ShellError::GenericError { error: "Error casting to string".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], })?; let res = chunked .scatter_single(indices, Some(val.as_ref())) .map_err(|e| ShellError::GenericError { error: "Error setting value".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], })?; let mut res = res.into_series(); res.rename("string".into()); NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head) } _ => Err(ShellError::GenericError { error: "Incorrect value type".into(), msg: format!( "this value cannot be set in a series of type '{}'", series.dtype() ), span: Some(span), help: None, inner: vec![], }), }?; res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&SetWithIndex) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/index/arg_sort.rs
crates/nu_plugin_polars/src/dataframe/command/index/arg_sort.rs
use crate::{ PolarsPlugin, values::{CustomValueSupport, PolarsPluginType}, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::prelude::{IntoSeries, SortOptions}; #[derive(Clone)] pub struct ArgSort; impl PluginCommand for ArgSort { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars arg-sort" } fn description(&self) -> &str { "Returns indexes for a sorted series." } fn search_terms(&self) -> Vec<&str> { vec!["argsort", "order", "arrange"] } fn signature(&self) -> Signature { Signature::build(self.name()) .switch("reverse", "reverse order", Some('r')) .switch("nulls-last", "nulls ordered last", Some('n')) .named( "limit", SyntaxShape::Int, "Limit a sort output, this is for optimization purposes and might be ignored.", Some('l'), ) .switch( "maintain-order", "maintain order on sorted items", Some('m'), ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns indexes for a sorted series", example: "[1 2 2 3 3] | polars into-df | polars arg-sort", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "arg_sort".to_string(), vec![ Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_int(3), Value::test_int(4), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns indexes for a sorted series", example: "[1 2 2 3 3] | polars into-df | polars arg-sort --reverse", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "arg_sort".to_string(), vec![ Value::test_int(3), Value::test_int(4), Value::test_int(1), Value::test_int(2), Value::test_int(0), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns indexes for a sorted series and applying a limit", example: "[1 2 2 3 3] | polars into-df | polars arg-sort --limit 2", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "arg_sort".to_string(), vec![Value::test_int(0), Value::test_int(1)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { command(plugin, engine, call, input).map_err(LabeledError::from) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let limit: Option<u64> = call.get_flag("limit")?; let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let sort_options = SortOptions { descending: call.has_flag("reverse")?, nulls_last: call.has_flag("nulls-last")?, multithreaded: true, maintain_order: call.has_flag("maintain-order")?, limit, }; let mut res = df .as_series(call.head)? .arg_sort(sort_options) .into_series(); res.rename("arg_sort".into()); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ArgSort) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/index/mod.rs
crates/nu_plugin_polars/src/dataframe/command/index/mod.rs
mod arg_max; mod arg_min; mod arg_sort; mod arg_unique; mod set_with_idx; use crate::PolarsPlugin; use nu_plugin::PluginCommand; pub use arg_max::ArgMax; pub use arg_min::ArgMin; pub use arg_sort::ArgSort; pub use arg_unique::ArgUnique; pub use set_with_idx::SetWithIndex; pub(crate) fn index_commands() -> Vec<Box<dyn PluginCommand<Plugin = PolarsPlugin>>> { vec![ Box::new(ArgMax), Box::new(ArgMin), Box::new(ArgSort), Box::new(ArgUnique), Box::new(SetWithIndex), ] }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/index/arg_unique.rs
crates/nu_plugin_polars/src/dataframe/command/index/arg_unique.rs
use crate::{ PolarsPlugin, values::{CustomValueSupport, PolarsPluginType}, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; use polars::prelude::IntoSeries; #[derive(Clone)] pub struct ArgUnique; impl PluginCommand for ArgUnique { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars arg-unique" } fn description(&self) -> &str { "Returns indexes for unique values." } fn search_terms(&self) -> Vec<&str> { vec!["argunique", "distinct", "noduplicate", "unrepeated"] } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Returns indexes for unique values", example: "[1 2 2 3 3] | polars into-df | polars arg-unique", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "arg_unique".to_string(), vec![Value::test_int(0), Value::test_int(1), Value::test_int(3)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { command(plugin, engine, call, input).map_err(LabeledError::from) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let mut res = df .as_series(call.head)? .arg_unique() .map_err(|e| ShellError::GenericError { error: "Error extracting unique values".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })? .into_series(); res.rename("arg_unique".into()); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ArgUnique) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/index/arg_max.rs
crates/nu_plugin_polars/src/dataframe/command/index/arg_max.rs
use crate::{PolarsPlugin, values::CustomValueSupport}; use crate::values::{Column, NuDataFrame, PolarsPluginType}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; use polars::prelude::{ArgAgg, IntoSeries, NewChunkedArray, UInt32Chunked}; #[derive(Clone)] pub struct ArgMax; impl PluginCommand for ArgMax { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars arg-max" } fn description(&self) -> &str { "Return index for max value in series." } fn search_terms(&self) -> Vec<&str> { vec!["argmax", "maximum", "most", "largest", "greatest"] } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Returns index for max value", example: "[1 3 2] | polars into-df | polars arg-max", result: Some( NuDataFrame::try_from_columns( vec![Column::new("arg_max".to_string(), vec![Value::test_int(1)])], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { command(plugin, engine, call, input).map_err(LabeledError::from) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let series = df.as_series(call.head)?; let res = series.arg_max(); let chunked = match res { Some(index) => UInt32Chunked::from_slice("arg_max".into(), &[index as u32]), None => UInt32Chunked::from_slice("arg_max".into(), &[]), }; let res = chunked.into_series(); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ArgMax) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/list/contains.rs
crates/nu_plugin_polars/src/dataframe/command/list/contains.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; #[derive(Clone)] pub struct ListContains; impl PluginCommand for ListContains { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars list-contains" } fn description(&self) -> &str { "Checks if an element is contained in a list." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "element", SyntaxShape::Any, "Element to search for in the list", ) .input_output_types(vec![( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), )]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns boolean indicating if a literal element was found in a list column", example: "let df = [[a]; [[a,b,c]] [[b,c,d]] [[c,d,f]]] | polars into-df -s {a: list<str>}; let df2 = $df | polars with-column [(polars col a | polars list-contains (polars lit a) | polars as b)] | polars collect; $df2.b", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "b".to_string(), vec![ Value::test_bool(true), Value::test_bool(false), Value::test_bool(false), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns boolean indicating if an element from another column was found in a list column", example: "let df = [[a, b]; [[a,b,c], a] [[b,c,d], f] [[c,d,f], f]] | polars into-df -s {a: list<str>, b: str}; let df2 = $df | polars with-column [(polars col a | polars list-contains b | polars as c)] | polars collect; $df2.c", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "b".to_string(), vec![ Value::test_bool(true), Value::test_bool(false), Value::test_bool(true), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns boolean indicating if an element from another expression was found in a list column", example: "let df = [[a, b]; [[1,2,3], 4] [[2,4,1], 2] [[2,1,6], 3]] | polars into-df -s {a: list<i64>, b: i64}; let df2 = $df | polars with-column [(polars col a | polars list-contains ((polars col b) * 2) | polars as c)] | polars collect; $df2.c", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "b".to_string(), vec![ Value::test_bool(false), Value::test_bool(true), Value::test_bool(true), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), } ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err(&value, &[PolarsPluginType::NuExpression])), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let element = call.req(0)?; let expressions = NuExpression::extract_exprs(plugin, element)?; let single_expression = match expressions.as_slice() { [single] => single.clone(), _ => { return Err(ShellError::GenericError { error: "Expected a single polars expression".into(), msg: "Requires a single polars expressions or column name as argument".into(), span: Some(call.head), help: None, inner: vec![], }); } }; let res: NuExpression = expr .into_polars() .list() .contains(single_expression, true) .into(); res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ListContains) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/list/mod.rs
crates/nu_plugin_polars/src/dataframe/command/list/mod.rs
mod contains; use crate::PolarsPlugin; use nu_plugin::PluginCommand; pub use contains::ListContains; pub(crate) fn list_commands() -> Vec<Box<dyn PluginCommand<Plugin = PolarsPlugin>>> { vec![Box::new(ListContains)] }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/integer/mod.rs
crates/nu_plugin_polars/src/dataframe/command/integer/mod.rs
mod to_decimal; mod to_integer; use crate::PolarsPlugin; use nu_plugin::PluginCommand; pub use to_decimal::ToDecimal; pub use to_integer::ToInteger; pub(crate) fn integer_commands() -> Vec<Box<dyn PluginCommand<Plugin = PolarsPlugin>>> { vec![Box::new(ToDecimal), Box::new(ToInteger)] }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/integer/to_integer.rs
crates/nu_plugin_polars/src/dataframe/command/integer/to_integer.rs
use crate::{ PolarsPlugin, values::{ Column, CustomValueSupport, NuDataFrame, NuDataType, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::prelude::{DataType, Expr, lit}; #[derive(Clone)] pub struct ToInteger; impl PluginCommand for ToInteger { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars integer" } fn description(&self) -> &str { "Converts a string column into a integer column" } fn search_terms(&self) -> Vec<&str> { vec!["expression", "integer", "float"] } fn signature(&self) -> Signature { Signature::build(self.name()) .switch("strict", "Raises an error as opposed to converting to null", Some('s')) .optional( "base", SyntaxShape::Any, "An integer or expression representing the base (radix) of the number system (default is 10)", ) .optional( "dtype", SyntaxShape::Any, "Data type to cast to (defaults is i64)", ) .input_output_type( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Modifies strings to integer", example: "[[a b]; [1, '2']] | polars into-df | polars select (polars col b | polars integer) | polars collect", result: Some( NuDataFrame::try_from_columns( vec![Column::new("b".to_string(), vec![Value::test_int(2)])], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuExpression(expr) => command(plugin, engine, call, expr), _ => Err(cant_convert_err(&value, &[PolarsPluginType::NuExpression])), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let strict: bool = call.has_flag("strict")?; let base: Expr = call .opt(0)? .map(|ref v| NuExpression::try_from_value(plugin, v)) .transpose()? .map(|e| e.into_polars()) .unwrap_or(lit(10)); let dtype: Option<DataType> = call .opt(1)? .map(|ref v| NuDataType::try_from_value(plugin, v)) .transpose()? .map(|dt| dt.to_polars()); let res: NuExpression = expr .into_polars() .str() .to_integer(base, dtype, strict) .into(); res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ToInteger) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/integer/to_decimal.rs
crates/nu_plugin_polars/src/dataframe/command/integer/to_decimal.rs
use crate::{ PolarsPlugin, values::{ Column, CustomValueSupport, NuDataFrame, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::prelude::DataType; #[derive(Clone)] pub struct ToDecimal; impl PluginCommand for ToDecimal { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars decimal" } fn description(&self) -> &str { "Converts a string column into a decimal column" } fn search_terms(&self) -> Vec<&str> { vec!["expression", "decimal", "float"] } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "infer_length", SyntaxShape::Int, "Number of decimal points to infer", ) .input_output_type( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Modifies strings to decimal", example: "[[a b]; [1, '2.4']] | polars into-df | polars select (polars col b | polars decimal 2) | polars collect", result: Some( NuDataFrame::try_from_columns( vec![Column::new("b".to_string(), vec![Value::test_float(2.40)])], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuExpression(expr) => command(plugin, engine, call, expr), _ => Err(cant_convert_err(&value, &[PolarsPluginType::NuExpression])), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let infer_length: usize = call.req(0)?; let res: NuExpression = expr .into_polars() .str() .to_decimal(infer_length) // since there isn't a good way to support actual large decimal types // in nushell, just cast it to an f64. .cast(DataType::Float64) .into(); res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ToDecimal) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/computation/math.rs
crates/nu_plugin_polars/src/dataframe/command/computation/math.rs
use crate::{PolarsPlugin, values::CustomValueSupport}; use crate::values::{ NuDataFrame, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Value, }; use polars::prelude::{Expr, Literal, df}; enum FunctionType { Abs, Cos, Dot, Exp, Log, Log1p, Sign, Sin, Sqrt, } impl FunctionType { fn from_str(func_type: &str, span: Span) -> Result<Self, ShellError> { match func_type { "abs" => Ok(Self::Abs), "cos" => Ok(Self::Cos), "dot" => Ok(Self::Dot), "exp" => Ok(Self::Exp), "log" => Ok(Self::Log), "log1p" => Ok(Self::Log1p), "sign" => Ok(Self::Sign), "sin" => Ok(Self::Sin), "sqrt" => Ok(Self::Sqrt), _ => Err(ShellError::GenericError { error: "Invalid function name".into(), msg: "".into(), span: Some(span), help: Some("See description for accepted functions".into()), inner: vec![], }), } } #[allow(dead_code)] fn to_str(&self) -> &'static str { match self { FunctionType::Abs => "abs", FunctionType::Cos => "cos", FunctionType::Dot => "dot", FunctionType::Exp => "exp", FunctionType::Log => "log", FunctionType::Log1p => "log1p", FunctionType::Sign => "sign", FunctionType::Sin => "sin", FunctionType::Sqrt => "sqrt", } } } #[derive(Clone)] pub struct ExprMath; impl PluginCommand for ExprMath { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars math" } fn description(&self) -> &str { "Collection of math functions to be applied on one or more column expressions" } fn extra_description(&self) -> &str { r#"This is an incomplete implementation of the available functions listed here: https://docs.pola.rs/api/python/stable/reference/expressions/computation.html. The following functions are currently available: - abs - cos - dot <expression> - exp - log <base; default e> - log1p - sign - sin - sqrt "# } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "type", SyntaxShape::String, "Function name. See extra description for full list of accepted values", ) .rest( "args", SyntaxShape::Any, "Extra arguments required by some functions", ) .input_output_types(vec![( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), )]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Apply function to column expression", example: "[[a]; [0] [-1] [2] [-3] [4]] | polars into-df | polars select [ (polars col a | polars math abs | polars as a_abs) (polars col a | polars math sign | polars as a_sign) (polars col a | polars math exp | polars as a_exp)] | polars collect", result: Some( NuDataFrame::from( df!( "a_abs" => [0, 1, 2, 3, 4], "a_sign" => [0, -1, 1, -1, 1], "a_exp" => [1.000, 0.36787944117144233, 7.38905609893065, 0.049787068367863944, 54.598150033144236], ) .expect("simple df for test should not fail"), ) .into_value(Span::test_data()), ), }, Example { description: "Specify arguments for select functions. See description for more information.", example: "[[a]; [0] [1] [2] [4] [8] [16]] | polars into-df | polars select [ (polars col a | polars math log 2 | polars as a_base2)] | polars collect", result: Some( NuDataFrame::from( df!( "a_base2" => [f64::NEG_INFINITY, 0.0, 1.0, 2.0, 3.0, 4.0], ) .expect("simple df for test should not fail"), ) .into_value(Span::test_data()), ), }, Example { description: "Specify arguments for select functions. See description for more information.", example: "[[a b]; [0 0] [1 1] [2 2] [3 3] [4 4] [5 5]] | polars into-df | polars select [ (polars col a | polars math dot (polars col b) | polars as ab)] | polars collect", result: Some( NuDataFrame::from( df!( "ab" => [55.0], ) .expect("simple df for test should not fail"), ) .into_value(Span::test_data()), ), } ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; let func_type: Spanned<String> = call.req(0)?; let func_type = FunctionType::from_str(&func_type.item, func_type.span)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuExpression(expr) => { command_expr(plugin, engine, call, func_type, expr) } _ => Err(cant_convert_err(&value, &[PolarsPluginType::NuExpression])), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, func_type: FunctionType, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let res = expr.into_polars(); let res: NuExpression = match func_type { FunctionType::Abs => res.abs(), FunctionType::Cos => res.cos(), FunctionType::Dot => { let expr: Expr = match call.rest::<Value>(1)?.first() { None => { return Err(ShellError::GenericError { error: "Second expression to compute dot product with must be provided" .into(), msg: "".into(), span: Some(call.head), help: None, inner: vec![], }); } Some(value) => NuExpression::try_from_value(plugin, value)?.into_polars(), }; res.dot(expr) } FunctionType::Exp => res.exp(), FunctionType::Log => { let base: Expr = match call.rest::<Value>(1)?.first() { // default natural log None => std::f64::consts::E.lit(), Some(value) => NuExpression::try_from_value(plugin, value)?.into_polars(), }; res.log(base) } FunctionType::Log1p => res.log1p(), FunctionType::Sign => res.sign(), FunctionType::Sin => res.sin(), FunctionType::Sqrt => res.sqrt(), } .into(); res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ExprMath) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/computation/mod.rs
crates/nu_plugin_polars/src/dataframe/command/computation/mod.rs
mod math; use crate::PolarsPlugin; use nu_plugin::PluginCommand; use math::ExprMath; pub(crate) fn computation_commands() -> Vec<Box<dyn PluginCommand<Plugin = PolarsPlugin>>> { vec![Box::new(ExprMath)] }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/boolean/is_duplicated.rs
crates/nu_plugin_polars/src/dataframe/command/boolean/is_duplicated.rs
use crate::{ PolarsPlugin, values::{CustomValueSupport, PolarsPluginType}, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; use polars::prelude::IntoSeries; #[derive(Clone)] pub struct IsDuplicated; impl PluginCommand for IsDuplicated { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars is-duplicated" } fn description(&self) -> &str { "Creates mask indicating duplicated values." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Create mask indicating duplicated values", example: "[5 6 6 6 8 8 8] | polars into-df | polars is-duplicated", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "is_duplicated".to_string(), vec![ Value::test_bool(false), Value::test_bool(true), Value::test_bool(true), Value::test_bool(true), Value::test_bool(true), Value::test_bool(true), Value::test_bool(true), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Create mask indicating duplicated rows in a dataframe", example: "[[a, b]; [1 2] [1 2] [3 3] [3 3] [1 1]] | polars into-df | polars is-duplicated", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "is_duplicated".to_string(), vec![ Value::test_bool(true), Value::test_bool(true), Value::test_bool(true), Value::test_bool(true), Value::test_bool(false), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let mut res = df .as_ref() .is_duplicated() .map_err(|e| ShellError::GenericError { error: "Error finding duplicates".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })? .into_series(); res.rename("is_duplicated".into()); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&IsDuplicated) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/boolean/is_unique.rs
crates/nu_plugin_polars/src/dataframe/command/boolean/is_unique.rs
use crate::{ PolarsPlugin, values::{CustomValueSupport, PolarsPluginType}, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; use polars::prelude::IntoSeries; #[derive(Clone)] pub struct IsUnique; impl PluginCommand for IsUnique { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars is-unique" } fn description(&self) -> &str { "Creates mask indicating unique values." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Create mask indicating unique values", example: "[5 6 6 6 8 8 8] | polars into-df | polars is-unique", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "is_unique".to_string(), vec![ Value::test_bool(true), Value::test_bool(false), Value::test_bool(false), Value::test_bool(false), Value::test_bool(false), Value::test_bool(false), Value::test_bool(false), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Create mask indicating duplicated rows in a dataframe", example: "[[a, b]; [1 2] [1 2] [3 3] [3 3] [1 1]] | polars into-df | polars is-unique", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "is_unique".to_string(), vec![ Value::test_bool(false), Value::test_bool(false), Value::test_bool(false), Value::test_bool(false), Value::test_bool(true), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let mut res = df .as_ref() .is_unique() .map_err(|e| ShellError::GenericError { error: "Error finding unique values".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })? .into_series(); res.rename("is_unique".into()); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&IsUnique) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/boolean/is_null.rs
crates/nu_plugin_polars/src/dataframe/command/boolean/is_null.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; use polars::prelude::IntoSeries; #[derive(Clone)] pub struct IsNull; impl PluginCommand for IsNull { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars is-null" } fn description(&self) -> &str { "Creates mask where value is null." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Create mask where values are null", example: r#"let s = ([5 6 0 8] | polars into-df); let res = ($s / $s); $res | polars is-null"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "is_null".to_string(), vec![ Value::test_bool(false), Value::test_bool(false), Value::test_bool(true), Value::test_bool(false), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Creates a is null expression from a column", example: "polars col a | polars is-null", result: None, }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => { command(plugin, engine, call, lazy.collect(call.head)?) } PolarsPluginObject::NuExpression(expr) => { let expr: NuExpression = expr.into_polars().is_null().into(); expr.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let mut res = df.as_series(call.head)?.is_null(); res.rename("is_null".into()); let df = NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&IsNull) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/boolean/otherwise.rs
crates/nu_plugin_polars/src/dataframe/command/boolean/otherwise.rs
use crate::{ PolarsPlugin, dataframe::values::{Column, NuDataFrame, NuExpression, NuWhen, NuWhenType}, values::{CustomValueSupport, PolarsPluginType}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, Signature, Span, SyntaxShape, Type, Value, }; #[derive(Clone)] pub struct ExprOtherwise; impl PluginCommand for ExprOtherwise { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars otherwise" } fn description(&self) -> &str { "Completes a when expression." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "otherwise expression", SyntaxShape::Any, "expression to apply when no when predicate matches", ) .input_output_type(Type::Any, PolarsPluginType::NuExpression.into()) .category(Category::Custom("expression".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Create a when conditions", example: "polars when ((polars col a) > 2) 4 | polars otherwise 5", result: None, }, Example { description: "Create a when conditions", example: "polars when ((polars col a) > 2) 4 | polars when ((polars col a) < 0) 6 | polars otherwise 0", result: None, }, Example { description: "Create a new column for the dataframe", example: r#"[[a b]; [6 2] [1 4] [4 1]] | polars into-lazy | polars with-column ( polars when ((polars col a) > 2) 4 | polars otherwise 5 | polars as c ) | polars with-column ( polars when ((polars col a) > 5) 10 | polars when ((polars col a) < 2) 6 | polars otherwise 0 | polars as d ) | polars collect"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(6), Value::test_int(1), Value::test_int(4)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(4), Value::test_int(1)], ), Column::new( "c".to_string(), vec![Value::test_int(4), Value::test_int(5), Value::test_int(4)], ), Column::new( "d".to_string(), vec![Value::test_int(10), Value::test_int(6), Value::test_int(0)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn search_terms(&self) -> Vec<&str> { vec!["condition", "else"] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let otherwise_predicate: Value = call.req(0)?; let otherwise_predicate = NuExpression::try_from_value(plugin, &otherwise_predicate)?; let value = input.into_value(call.head)?; let complete: NuExpression = match NuWhen::try_from_value(plugin, &value)?.when_type { NuWhenType::Then(then) => then.otherwise(otherwise_predicate.into_polars()).into(), NuWhenType::ChainedThen(chained_when) => chained_when .otherwise(otherwise_predicate.into_polars()) .into(), }; complete .to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { test_polars_plugin_command(&ExprOtherwise) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/boolean/is_not_null.rs
crates/nu_plugin_polars/src/dataframe/command/boolean/is_not_null.rs
use crate::{ PolarsPlugin, values::{CustomValueSupport, PolarsPluginObject, PolarsPluginType, cant_convert_err}, }; use super::super::super::values::{Column, NuDataFrame, NuExpression}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; use polars::prelude::IntoSeries; #[derive(Clone)] pub struct IsNotNull; impl PluginCommand for IsNotNull { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars is-not-null" } fn description(&self) -> &str { "Creates mask where value is not null." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Create mask where values are not null", example: r#"let s = ([5 6 0 8] | polars into-df); let res = ($s / $s); $res | polars is-not-null"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "is_not_null".to_string(), vec![ Value::test_bool(true), Value::test_bool(true), Value::test_bool(false), Value::test_bool(true), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Creates a is not null expression from a column", example: "polars col a | polars is-not-null", result: None, }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => { command(plugin, engine, call, lazy.collect(call.head)?) } PolarsPluginObject::NuExpression(expr) => { let expr: NuExpression = expr.into_polars().is_not_null().into(); expr.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let mut res = df.as_series(call.head)?.is_not_null(); res.rename("is_not_null".into()); let df = NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&IsNotNull) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/boolean/not.rs
crates/nu_plugin_polars/src/dataframe/command/boolean/not.rs
use crate::{ PolarsPlugin, values::{CustomValueSupport, PolarsPluginType}, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; use polars::prelude::IntoSeries; use std::ops::Not; #[derive(Clone)] pub struct NotSeries; impl PluginCommand for NotSeries { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars not" } fn description(&self) -> &str { "Inverts boolean mask." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Inverts boolean mask", example: "[true false true] | polars into-df | polars not", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_bool(false), Value::test_bool(true), Value::test_bool(false), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; command(plugin, engine, call, df) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let series = df.as_series(call.head)?; let bool = series.bool().map_err(|e| ShellError::GenericError { error: "Error inverting mask".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let res = bool.not(); let df = NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&NotSeries) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/boolean/expr_not.rs
crates/nu_plugin_polars/src/dataframe/command/boolean/expr_not.rs
use crate::PolarsPlugin; use crate::dataframe::values::NuExpression; use crate::values::{ CustomValueSupport, NuDataFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, ShellError, Signature, Span}; use polars::df; pub struct ExprNot; impl PluginCommand for ExprNot { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars expr-not" } fn description(&self) -> &str { "Creates a not expression." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), )]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Creates a not expression", example: "(polars col a) > 2) | polars expr-not", result: None, }, Example { description: "Adds a column showing which values of col a are not greater than 2", example: "[[a]; [1] [2] [3] [4] [5]] | polars into-df | polars with-column [(((polars col a) > 2) | polars expr-not | polars as a_expr_not)] | polars collect | polars sort-by a", result: Some( NuDataFrame::from( df!( "a" => [1, 2, 3, 4, 5], "b" => [true, true, false, false, false] ) .expect("should not fail"), ) .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err(&value, &[PolarsPluginType::NuExpression])), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { NuExpression::from(expr.into_polars().not()).to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; use nu_protocol::ShellError; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ExprNot) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/boolean/when.rs
crates/nu_plugin_polars/src/dataframe/command/boolean/when.rs
use crate::{ PolarsPlugin, dataframe::values::{Column, NuDataFrame, NuExpression, NuWhen}, values::{CustomValueSupport, NuWhenType, PolarsPluginType}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, Signature, Span, SyntaxShape, Type, Value, }; use polars::prelude::when; #[derive(Clone)] pub struct ExprWhen; impl PluginCommand for ExprWhen { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars when" } fn description(&self) -> &str { "Creates and modifies a when expression." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "when expression", SyntaxShape::Any, "when expression used for matching", ) .required( "then expression", SyntaxShape::Any, "expression that will be applied when predicate is true", ) .input_output_types(vec![ (Type::Nothing, PolarsPluginType::NuExpression.into()), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), // FIXME Type::Any input added to disable pipeline input type checking, as run-time checks can raise undesirable type errors // which aren't caught by the parser. see https://github.com/nushell/nushell/pull/14922 for more details (Type::Any, PolarsPluginType::NuExpression.into()), ]) .category(Category::Custom("expression".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Create a when conditions", example: "polars when ((polars col a) > 2) 4", result: None, }, Example { description: "Create a when conditions", example: "polars when ((polars col a) > 2) 4 | polars when ((polars col a) < 0) 6", result: None, }, Example { description: "Create a new column for the dataframe", example: r#"[[a b]; [6 2] [1 4] [4 1]] | polars into-lazy | polars with-column ( polars when ((polars col a) > 2) 4 | polars otherwise 5 | polars as c ) | polars with-column ( polars when ((polars col a) > 5) 10 | polars when ((polars col a) < 2) 6 | polars otherwise 0 | polars as d ) | polars collect"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(6), Value::test_int(1), Value::test_int(4)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(4), Value::test_int(1)], ), Column::new( "c".to_string(), vec![Value::test_int(4), Value::test_int(5), Value::test_int(4)], ), Column::new( "d".to_string(), vec![Value::test_int(10), Value::test_int(6), Value::test_int(0)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn search_terms(&self) -> Vec<&str> { vec!["condition", "match", "if", "else"] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let when_predicate: Value = call.req(0)?; let when_predicate = NuExpression::try_from_value(plugin, &when_predicate)?; let then_predicate: Value = call.req(1)?; let then_predicate = NuExpression::try_from_value(plugin, &then_predicate)?; let value = input.into_value(call.head)?; let when_then: NuWhen = match value { Value::Nothing { .. } => when(when_predicate.into_polars()) .then(then_predicate.into_polars()) .into(), v => match NuWhen::try_from_value(plugin, &v)?.when_type { NuWhenType::Then(when_then) => when_then .when(when_predicate.into_polars()) .then(then_predicate.into_polars()) .into(), NuWhenType::ChainedThen(when_then_then) => when_then_then .when(when_predicate.into_polars()) .then(then_predicate.into_polars()) .into(), }, }; when_then .to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { test_polars_plugin_command(&ExprWhen) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/boolean/arg_true.rs
crates/nu_plugin_polars/src/dataframe/command/boolean/arg_true.rs
use crate::{ PolarsPlugin, values::{CustomValueSupport, PolarsPluginType}, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; use polars::prelude::{IntoLazy, arg_where, col}; #[derive(Clone)] pub struct ArgTrue; impl PluginCommand for ArgTrue { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars arg-true" } fn description(&self) -> &str { "Returns indexes where values are true." } fn search_terms(&self) -> Vec<&str> { vec!["argtrue", "truth", "boolean-true"] } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Returns indexes where values are true", example: "[false true false] | polars into-df | polars arg-true", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "arg_true".to_string(), vec![Value::test_int(1)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let columns = df.as_ref().get_column_names(); if columns.len() > 1 { return Err(ShellError::GenericError { error: "Error using as series".into(), msg: "dataframe has more than one column".into(), span: Some(call.head), help: None, inner: vec![], }); } match columns.first() { Some(column) => { let expression = arg_where(col((*column).clone()).eq(true)).alias("arg_true"); let res: NuDataFrame = df .as_ref() .clone() .lazy() .select(&[expression]) .collect() .map_err(|err| ShellError::GenericError { error: "Error creating index column".into(), msg: err.to_string(), span: Some(call.head), help: None, inner: vec![], })? .into(); res.to_pipeline_data(plugin, engine, call.head) } _ => Err(ShellError::UnsupportedInput { msg: "Expected the dataframe to have a column".to_string(), input: "".to_string(), msg_span: call.head, input_span: call.head, }), } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ArgTrue) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/boolean/mod.rs
crates/nu_plugin_polars/src/dataframe/command/boolean/mod.rs
mod all_false; mod all_true; mod arg_true; mod expr_not; mod is_duplicated; mod is_in; mod is_not_null; mod is_null; mod is_unique; mod not; pub(crate) mod otherwise; mod set; mod when; use crate::PolarsPlugin; use nu_plugin::PluginCommand; pub use all_false::AllFalse; pub use arg_true::ArgTrue; pub use is_duplicated::IsDuplicated; pub use is_in::ExprIsIn; pub use is_not_null::IsNotNull; pub use is_null::IsNull; pub use is_unique::IsUnique; pub use not::NotSeries; pub use otherwise::ExprOtherwise; pub use set::SetSeries; pub use when::ExprWhen; pub(crate) fn boolean_commands() -> Vec<Box<dyn PluginCommand<Plugin = PolarsPlugin>>> { vec![ Box::new(AllFalse), Box::new(all_true::AllTrue), Box::new(ArgTrue), Box::new(ExprIsIn), Box::new(ExprOtherwise), Box::new(ExprWhen), Box::new(expr_not::ExprNot), Box::new(IsDuplicated), Box::new(IsNotNull), Box::new(IsNull), Box::new(IsUnique), Box::new(NotSeries), Box::new(SetSeries), ] }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/boolean/all_true.rs
crates/nu_plugin_polars/src/dataframe/command/boolean/all_true.rs
use crate::PolarsPlugin; use crate::values::{Column, CustomValueSupport, NuDataFrame, PolarsPluginType}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; #[derive(Clone)] pub struct AllTrue; impl PluginCommand for AllTrue { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars all-true" } fn description(&self) -> &str { "Returns true if all values are true." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns true if all values are true", example: "[true true true] | polars into-df | polars all-true", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "all_true".to_string(), vec![Value::test_bool(true)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Checks the result from a comparison", example: r#"let s = ([5 6 2 8] | polars into-df); let res = ($s > 9); $res | polars all-true"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "all_true".to_string(), vec![Value::test_bool(false)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let series = df.as_series(call.head)?; let bool = series.bool().map_err(|_| ShellError::GenericError { error: "Error converting to bool".into(), msg: "all-false only works with series of type bool".into(), span: Some(call.head), help: None, inner: vec![], })?; let value = Value::bool(bool.all(), call.head); let df = NuDataFrame::try_from_columns( vec![Column::new("all_true".to_string(), vec![value])], None, )?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&AllTrue) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/boolean/all_false.rs
crates/nu_plugin_polars/src/dataframe/command/boolean/all_false.rs
use crate::PolarsPlugin; use crate::values::{Column, CustomValueSupport, NuDataFrame, PolarsPluginType}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; #[derive(Clone)] pub struct AllFalse; impl PluginCommand for AllFalse { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars all-false" } fn description(&self) -> &str { "Returns true if all values are false." } fn signature(&self) -> Signature { Signature::build(self.name()) .category(Category::Custom("dataframe".into())) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns true if all values are false", example: "[false false false] | polars into-df | polars all-false", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "all_false".to_string(), vec![Value::test_bool(true)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Checks the result from a comparison", example: r#"let s = ([5 6 2 10] | polars into-df); let res = ($s > 9); $res | polars all-false"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "all_false".to_string(), vec![Value::test_bool(false)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let series = df.as_series(call.head)?; let bool = series.bool().map_err(|_| ShellError::GenericError { error: "Error converting to bool".into(), msg: "all-false only works with series of type bool".into(), span: Some(call.head), help: None, inner: vec![], })?; let value = Value::bool(!bool.any(), call.head); let df = NuDataFrame::try_from_columns( vec![Column::new("all_false".to_string(), vec![value])], None, )?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&AllFalse) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/boolean/set.rs
crates/nu_plugin_polars/src/dataframe/command/boolean/set.rs
use crate::{ PolarsPlugin, missing_flag_error, values::{CustomValueSupport, PolarsPluginType}, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::prelude::{ChunkSet, DataType, IntoSeries}; #[derive(Clone)] pub struct SetSeries; impl PluginCommand for SetSeries { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars set" } fn description(&self) -> &str { "Sets value where given mask is true." } fn signature(&self) -> Signature { Signature::build(self.name()) .required("value", SyntaxShape::Any, "value to be inserted in series") .required_named( "mask", SyntaxShape::Any, "mask indicating insertions", Some('m'), ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Shifts the values by a given period", example: r#"let s = ([1 2 2 3 3] | polars into-df | polars shift 2); let mask = ($s | polars is-null); $s | polars set 0 --mask $mask"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_int(0), Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_int(2), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let value: Value = call.req(0)?; let mask_value: Value = call .get_flag("mask")? .ok_or_else(|| missing_flag_error("mask", call.head))?; let mask_span = mask_value.span(); let mask = NuDataFrame::try_from_value_coerce(plugin, &mask_value, call.head)?.as_series(mask_span)?; let bool_mask = match mask.dtype() { DataType::Boolean => mask.bool().map_err(|e| ShellError::GenericError { error: "Error casting to bool".into(), msg: e.to_string(), span: Some(mask_span), help: None, inner: vec![], }), _ => Err(ShellError::GenericError { error: "Incorrect type".into(), msg: "can only use bool series as mask".into(), span: Some(mask_span), help: None, inner: vec![], }), }?; let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let series = df.as_series(call.head)?; let span = value.span(); let res = match value { Value::Int { val, .. } => { let chunked = series.i64().map_err(|e| ShellError::GenericError { error: "Error casting to i64".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], })?; let res = chunked .set(bool_mask, Some(val)) .map_err(|e| ShellError::GenericError { error: "Error setting value".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], })?; NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head) } Value::Float { val, .. } => { let chunked = series.f64().map_err(|e| ShellError::GenericError { error: "Error casting to f64".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], })?; let res = chunked .set(bool_mask, Some(val)) .map_err(|e| ShellError::GenericError { error: "Error setting value".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], })?; NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head) } Value::String { val, .. } => { let chunked = series.str().map_err(|e| ShellError::GenericError { error: "Error casting to string".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], })?; let res = chunked.set(bool_mask, Some(val.as_ref())).map_err(|e| { ShellError::GenericError { error: "Error setting value".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], } })?; let mut res = res.into_series(); res.rename("string".into()); NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head) } _ => Err(ShellError::GenericError { error: "Incorrect value type".into(), msg: format!( "this value cannot be set in a series of type '{}'", series.dtype() ), span: Some(span), help: None, inner: vec![], }), }?; res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&SetSeries) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/boolean/is_in.rs
crates/nu_plugin_polars/src/dataframe/command/boolean/is_in.rs
use crate::{ PolarsPlugin, dataframe::values::{Column, NuDataFrame, NuExpression}, values::{CustomValueSupport, PolarsPluginObject, PolarsPluginType, cant_convert_err}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::prelude::{DataType, Expr, lit}; #[derive(Clone)] pub struct ExprIsIn; impl PluginCommand for ExprIsIn { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars is-in" } fn description(&self) -> &str { "Creates an is-in expression or checks to see if the elements are contained in the right series" } fn signature(&self) -> Signature { Signature::build(self.name()) .required("list", SyntaxShape::Any, "List to check if values are in") .input_output_types(vec![( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), )]) .category(Category::Custom("expression".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Creates a is-in expression using a list", example: r#"let df = ([[a b]; [one 1] [two 2] [three 3]] | polars into-df); $df | polars with-column (polars col a | polars is-in [one two] | polars as a_in)"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![ Value::test_string("one"), Value::test_string("two"), Value::test_string("three"), ], ), Column::new( "b".to_string(), vec![Value::test_int(1), Value::test_int(2), Value::test_int(3)], ), Column::new( "a_in".to_string(), vec![ Value::test_bool(true), Value::test_bool(true), Value::test_bool(false), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Creates a is-in expression using a polars series", example: r#"let df = ([[a b]; [one 1] [two 2] [three 3]] | polars into-df); $df | polars with-column (polars col a | polars is-in ([one two] | polars into-df) | polars as a_in)"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![ Value::test_string("one"), Value::test_string("two"), Value::test_string("three"), ], ), Column::new( "b".to_string(), vec![Value::test_int(1), Value::test_int(2), Value::test_int(3)], ), Column::new( "a_in".to_string(), vec![ Value::test_bool(true), Value::test_bool(true), Value::test_bool(false), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Creates a is-in expression using a polars expr", example: r#"let df = ([[a b]; [one 1] [two 2] [three 3]] | polars into-df); $df | polars with-column (polars col a | polars is-in (polars lit [one two] | polars implode) | polars as a_in)"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![ Value::test_string("one"), Value::test_string("two"), Value::test_string("three"), ], ), Column::new( "b".to_string(), vec![Value::test_int(1), Value::test_int(2), Value::test_int(3)], ), Column::new( "a_in".to_string(), vec![ Value::test_bool(true), Value::test_bool(true), Value::test_bool(false), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn search_terms(&self) -> Vec<&str> { vec!["check", "contained", "is-contain", "match"] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let is_in_expr: Expr = call .req::<Value>(0) .and_then(|ref value| NuExpression::try_from_value(plugin, value)) .map(|expr| expr.into_polars()) .or_else(|_| { let values: NuDataFrame = call .req::<Value>(0) .and_then(|ref value| NuDataFrame::try_from_value(plugin, value)) .or_else(|_| { call.req::<Vec<Value>>(0).and_then(|list| { NuDataFrame::try_from_columns( vec![Column::new("list".to_string(), list)], None, ) }) })?; let list = values.as_series(call.head)?; if matches!(list.dtype(), DataType::Object(..)) { Err(ShellError::IncompatibleParametersSingle { msg: "Cannot use a mixed list as argument".into(), span: call.head, }) } else { Ok(lit(list).implode()) } })?; let expr: NuExpression = expr.into_polars().is_in(is_in_expr, true).into(); expr.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ExprIsIn) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/groupby.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/groupby.rs
use crate::{ PolarsPlugin, dataframe::values::{NuDataFrame, NuExpression, NuLazyFrame, NuLazyGroupBy}, values::{CustomValueSupport, PolarsPluginType}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::{df, prelude::Expr}; #[derive(Clone)] pub struct ToLazyGroupBy; impl PluginCommand for ToLazyGroupBy { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars group-by" } fn description(&self) -> &str { "Creates a group-by object that can be used for other aggregations." } fn signature(&self) -> Signature { Signature::build(self.name()) .rest( "Group-by expressions", SyntaxShape::Any, "Expression(s) that define the lazy group-by", ) .switch( "maintain-order", "Ensure that the order of the groups is consistent with the input data. This is slower than a default group by and cannot be run on the streaming engine.", Some('m')) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Group by and perform an aggregation", example: r#"[[a b]; [1 2] [1 4] [2 6] [2 4]] | polars into-lazy | polars group-by a | polars agg [ (polars col b | polars min | polars as "b_min") (polars col b | polars max | polars as "b_max") (polars col b | polars sum | polars as "b_sum") ] | polars collect | polars sort-by a"#, result: Some( NuDataFrame::from( df!( "a" => &[1i64, 2], "b_min" => &[2i64, 4], "b_max" => &[4i64, 6], "b_sum" => &[6i64, 10], ) .expect("should not fail"), ) .into_value(Span::test_data()), ), }, Example { description: "Group by an expression and perform an aggregation", example: r#"[[a b]; [2025-04-01 1] [2025-04-02 2] [2025-04-03 3] [2025-04-04 4]] | polars into-lazy | polars group-by (polars col a | polars get-day | $in mod 2) | polars agg [ (polars col b | polars min | polars as "b_min") (polars col b | polars max | polars as "b_max") (polars col b | polars sum | polars as "b_sum") ] | polars collect | polars sort-by a"#, result: Some( NuDataFrame::from( df!( "a" => &[0i64, 1], "b_min" => &[2i64, 1], "b_max" => &[4i64, 3], "b_sum" => &[6i64, 4], ) .expect("should not fail"), ) .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let vals: Vec<Value> = call.rest(0)?; let expr_value = Value::list(vals, call.head); let expressions = NuExpression::extract_exprs(plugin, expr_value)?; let maintain_order = call.has_flag("maintain-order")?; if expressions .iter() .any(|expr| matches!(expr, Expr::Agg(..) | Expr::Window { .. })) { let value: Value = call.req(0)?; Err(ShellError::IncompatibleParametersSingle { msg: "Cannot group by an aggregation or window expression".into(), span: value.span(), })?; } let pipeline_value = input.into_value(call.head)?; let lazy = NuLazyFrame::try_from_value_coerce(plugin, &pipeline_value)?; command(plugin, engine, call, lazy, expressions, maintain_order) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, mut lazy: NuLazyFrame, expressions: Vec<Expr>, maintain_order: bool, ) -> Result<PipelineData, ShellError> { let group_by = if maintain_order { lazy.to_polars().group_by_stable(expressions) } else { lazy.to_polars().group_by(expressions) }; let group_by = NuLazyGroupBy::new(group_by, lazy.from_eager, lazy.schema().clone()?); group_by.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ToLazyGroupBy) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/count.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/count.rs
use crate::PolarsPlugin; use crate::dataframe::values::NuExpression; use crate::values::{ CustomValueSupport, NuDataFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, ShellError, Signature, Span}; use polars::df; pub struct ExprCount; impl PluginCommand for ExprCount { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars count" } fn description(&self) -> &str { "Returns the number of non-null values in the column." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), )]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Count the number of non-null values in a column", example: r#"[[a]; ["foo"] ["bar"] [null]] | polars into-df | polars select (polars col a | polars count) | polars collect"#, result: Some( NuDataFrame::from( df!( "a" => [2] ) .expect("should not fail"), ) .into_value(Span::unknown()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err(&value, &[PolarsPluginType::NuExpression])), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { NuExpression::from(expr.into_polars().count()).to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; use nu_protocol::ShellError; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ExprCount) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/quantile.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/quantile.rs
use crate::{ PolarsPlugin, dataframe::values::{Column, NuDataFrame, NuLazyFrame}, values::{ CustomValueSupport, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::prelude::{QuantileMethod, lit}; #[derive(Clone)] pub struct LazyQuantile; impl PluginCommand for LazyQuantile { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars quantile" } fn description(&self) -> &str { "Aggregates the columns to the selected quantile." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "quantile", SyntaxShape::Number, "quantile value for quantile operation", ) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "quantile value from columns in a dataframe", example: "[[a b]; [6 2] [1 4] [4 1]] | polars into-df | polars quantile 0.5", result: Some( NuDataFrame::try_from_columns( vec![ Column::new("a".to_string(), vec![Value::test_float(4.0)]), Column::new("b".to_string(), vec![Value::test_float(2.0)]), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Quantile aggregation for a group-by", example: r#"[[a b]; [one 2] [one 4] [two 1]] | polars into-df | polars group-by a | polars agg (polars col b | polars quantile 0.5) | polars collect | polars sort-by a"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_string("one"), Value::test_string("two")], ), Column::new( "b".to_string(), vec![Value::test_float(4.0), Value::test_float(1.0)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; let quantile: f64 = call.req(0)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => { command(plugin, engine, call, df.lazy(), quantile) } PolarsPluginObject::NuLazyFrame(lazy) => command(plugin, engine, call, lazy, quantile), PolarsPluginObject::NuExpression(expr) => { let expr: NuExpression = expr .into_polars() .quantile(lit(quantile), QuantileMethod::default()) .into(); expr.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, quantile: f64, ) -> Result<PipelineData, ShellError> { let lazy = NuLazyFrame::new( lazy.from_eager, lazy.to_polars() .quantile(lit(quantile), QuantileMethod::default()), ); lazy.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&LazyQuantile) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/median.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/median.rs
use crate::{ PolarsPlugin, dataframe::values::{Column, NuDataFrame, NuLazyFrame}, values::{ CustomValueSupport, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; #[derive(Clone)] pub struct LazyMedian; impl PluginCommand for LazyMedian { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars median" } fn description(&self) -> &str { "Median value from columns in a dataframe or creates expression for an aggregation" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Median aggregation for a group-by", example: r#"[[a b]; [one 2] [one 4] [two 1]] | polars into-df | polars group-by a | polars agg (polars col b | polars median) | polars collect | polars sort-by a"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_string("one"), Value::test_string("two")], ), Column::new( "b".to_string(), vec![Value::test_float(3.0), Value::test_float(1.0)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Median value from columns in a dataframe", example: "[[a b]; [6 2] [4 2] [2 2]] | polars into-df | polars median | polars collect", result: Some( NuDataFrame::try_from_columns( vec![ Column::new("a".to_string(), vec![Value::test_float(4.0)]), Column::new("b".to_string(), vec![Value::test_float(2.0)]), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command(plugin, engine, call, df.lazy()), PolarsPluginObject::NuLazyFrame(lazy) => command(plugin, engine, call, lazy), PolarsPluginObject::NuExpression(expr) => { let expr: NuExpression = expr.into_polars().median().into(); expr.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let polars_lazy = lazy.to_polars().median(); let lazy = NuLazyFrame::new(lazy.from_eager, polars_lazy); lazy.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&LazyMedian) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/horizontal.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/horizontal.rs
use crate::{ PolarsPlugin, values::{Column, CustomValueSupport, NuDataFrame, NuExpression, PolarsPluginType}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Type, Value, }; use polars::lazy::dsl::{ all_horizontal, any_horizontal, max_horizontal, mean_horizontal, min_horizontal, sum_horizontal, }; use polars::prelude::Expr; enum HorizontalType { All, Any, Min, Max, Sum, Mean, } impl HorizontalType { fn from_str(roll_type: &str, span: Span) -> Result<Self, ShellError> { match roll_type { "all" => Ok(Self::All), "any" => Ok(Self::Any), "min" => Ok(Self::Min), "max" => Ok(Self::Max), "sum" => Ok(Self::Sum), "mean" => Ok(Self::Mean), _ => Err(ShellError::GenericError { error: "Wrong operation".into(), msg: "Operation not valid for cumulative".into(), span: Some(span), help: Some("Allowed values: all, any, max, min, sum, mean".into()), inner: vec![], }), } } } #[derive(Clone)] pub struct Horizontal; impl PluginCommand for Horizontal { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars horizontal" } fn description(&self) -> &str { "Horizontal calculation across multiple columns." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type(Type::Any, PolarsPluginType::NuExpression.into()) .required( "type", SyntaxShape::String, "horizontal operation. Values of all, any, min, max, sum, and mean are accepted.", ) .rest( "Group-by expressions", SyntaxShape::Any, "Expression(s) that define the lazy group-by", ) .switch( "nulls", "If set, null value in the input will lead to null output", Some('n'), ) .category(Category::Custom("expression".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Horizontal sum across two columns (ignore nulls by default)", example: "[[a b]; [1 2] [2 3] [3 4] [4 5] [5 null]] | polars into-df | polars select (polars horizontal sum a b) | polars collect", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "sum".to_string(), vec![ Value::test_int(3), Value::test_int(5), Value::test_int(7), Value::test_int(9), Value::test_int(5), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Horizontal sum across two columns while accounting for nulls", example: "[[a b]; [1 2] [2 3] [3 4] [4 5] [5 null]] | polars into-df | polars select (polars horizontal sum a b --nulls) | polars collect", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "sum".to_string(), vec![ Value::test_int(3), Value::test_int(5), Value::test_int(7), Value::test_int(9), Value::test_nothing(), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, _input: PipelineData, ) -> Result<PipelineData, LabeledError> { let func_type: Spanned<String> = call.req(0)?; let func_type = HorizontalType::from_str(&func_type.item, func_type.span)?; let vals: Vec<Value> = call.rest(1)?; let expr_value = Value::list(vals, call.head); let exprs = NuExpression::extract_exprs(plugin, expr_value)?; let ignore_nulls = !call.has_flag("nulls")?; command(plugin, engine, call, func_type, exprs, ignore_nulls).map_err(LabeledError::from) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, func_type: HorizontalType, exprs: Vec<Expr>, ignore_nulls: bool, ) -> Result<PipelineData, ShellError> { let res: NuExpression = match func_type { HorizontalType::All => all_horizontal(exprs), HorizontalType::Any => any_horizontal(exprs), HorizontalType::Max => max_horizontal(exprs), HorizontalType::Min => min_horizontal(exprs), HorizontalType::Sum => sum_horizontal(exprs, ignore_nulls), HorizontalType::Mean => mean_horizontal(exprs, ignore_nulls), } .map_err(|e| ShellError::GenericError { error: "Cannot apply horizontal aggregation".to_string(), msg: "".into(), span: Some(call.head), help: Some(e.to_string()), inner: vec![], })? .into(); res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&Horizontal) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/cumulative.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/cumulative.rs
use crate::{PolarsPlugin, values::CustomValueSupport}; use crate::values::{ Column, NuDataFrame, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Value, }; use polars::prelude::{DataType, IntoSeries, cum_max, cum_min, cum_sum}; enum CumulativeType { Min, Max, Sum, } impl CumulativeType { fn from_str(roll_type: &str, span: Span) -> Result<Self, ShellError> { match roll_type { "min" => Ok(Self::Min), "max" => Ok(Self::Max), "sum" => Ok(Self::Sum), _ => Err(ShellError::GenericError { error: "Wrong operation".into(), msg: "Operation not valid for cumulative".into(), span: Some(span), help: Some("Allowed values: max, min, sum".into()), inner: vec![], }), } } fn to_str(&self) -> &'static str { match self { CumulativeType::Min => "cumulative_min", CumulativeType::Max => "cumulative_max", CumulativeType::Sum => "cumulative_sum", } } } #[derive(Clone)] pub struct Cumulative; impl PluginCommand for Cumulative { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars cumulative" } fn description(&self) -> &str { "Cumulative calculation for a column or series." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "type", SyntaxShape::String, "rolling operation. Values of min, max, and sum are accepted.", ) .switch("reverse", "Reverse cumulative calculation", Some('r')) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Cumulative sum for a column", example: "[[a]; [1] [2] [3] [4] [5]] | polars into-df | polars select (polars col a | polars cumulative sum | polars as cum_a) | polars collect", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "cum_a".to_string(), vec![ Value::test_int(1), Value::test_int(3), Value::test_int(6), Value::test_int(10), Value::test_int(15), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Cumulative sum for a series", example: "[1 2 3 4 5] | polars into-df | polars cumulative sum", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0_cumulative_sum".to_string(), vec![ Value::test_int(1), Value::test_int(3), Value::test_int(6), Value::test_int(10), Value::test_int(15), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Cumulative sum for a series in reverse order", example: "[1 2 3 4 5] | polars into-df | polars cumulative sum --reverse", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0_cumulative_sum".to_string(), vec![ Value::test_int(15), Value::test_int(14), Value::test_int(12), Value::test_int(9), Value::test_int(5), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; let cum_type: Spanned<String> = call.req(0)?; let cum_type = CumulativeType::from_str(&cum_type.item, cum_type.span)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_df(plugin, engine, call, cum_type, df), PolarsPluginObject::NuLazyFrame(lazy) => { command_df(plugin, engine, call, cum_type, lazy.collect(call.head)?) } PolarsPluginObject::NuExpression(expr) => { command_expr(plugin, engine, call, cum_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_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, cum_type: CumulativeType, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let reverse = call.has_flag("reverse")?; let polars = expr.into_polars(); let res: NuExpression = match cum_type { CumulativeType::Max => polars.cum_max(reverse), CumulativeType::Min => polars.cum_min(reverse), CumulativeType::Sum => polars.cum_sum(reverse), } .into(); res.to_pipeline_data(plugin, engine, call.head) } fn command_df( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, cum_type: CumulativeType, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let reverse = call.has_flag("reverse")?; let series = df.as_series(call.head)?; if let DataType::Object(..) = series.dtype() { return Err(ShellError::GenericError { error: "Found object series".into(), msg: "Series of type object cannot be used for cumulative operation".into(), span: Some(call.head), help: None, inner: vec![], }); } let mut res = match cum_type { CumulativeType::Max => cum_max(&series, reverse), CumulativeType::Min => cum_min(&series, reverse), CumulativeType::Sum => cum_sum(&series, reverse), } .map_err(|e| ShellError::GenericError { error: "Error creating cumulative".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let name = format!("{}_{}", series.name(), cum_type.to_str()); res.rename(name.into()); let df = NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&Cumulative) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/sum.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/sum.rs
use crate::PolarsPlugin; use crate::dataframe::values::NuExpression; use crate::values::{ Column, CustomValueSupport, NuDataFrame, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; pub struct ExprSum; impl PluginCommand for ExprSum { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars sum" } fn description(&self) -> &str { "Creates a sum expression for an aggregation or aggregates columns to their sum value." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Sums all columns in a dataframe", example: "[[a b]; [6 2] [1 4] [4 1]] | polars into-df | polars sum | polars collect", result: Some( NuDataFrame::try_from_columns( vec![ Column::new("a".to_string(), vec![Value::test_int(11)]), Column::new("b".to_string(), vec![Value::test_int(7)]), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Sum aggregation for a group-by", example: r#"[[a b]; [one 2] [one 4] [two 1]] | polars into-df | polars group-by a | polars agg (polars col b | polars sum) | polars collect | polars sort-by a"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_string("one"), Value::test_string("two")], ), Column::new( "b".to_string(), vec![Value::test_int(6), Value::test_int(1)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_lazy(plugin, engine, call, df.lazy()), PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { NuExpression::from(expr.into_polars().sum()).to_pipeline_data(plugin, engine, call.head) } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let res: NuLazyFrame = lazy.to_polars().sum().into(); res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; use nu_protocol::ShellError; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ExprSum) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/max.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/max.rs
use crate::PolarsPlugin; use crate::dataframe::values::NuExpression; use crate::values::{ Column, CustomValueSupport, NuDataFrame, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; pub struct ExprMax; impl PluginCommand for ExprMax { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars max" } fn description(&self) -> &str { "Creates a max expression or aggregates columns to their max value." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Max value from columns in a dataframe", example: "[[a b]; [6 2] [1 4] [4 1]] | polars into-df | polars max", result: Some( NuDataFrame::try_from_columns( vec![ Column::new("a".to_string(), vec![Value::test_int(6)]), Column::new("b".to_string(), vec![Value::test_int(4)]), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Max aggregation for a group-by", example: r#"[[a b]; [one 2] [one 4] [two 1]] | polars into-df | polars group-by a | polars agg (polars col b | polars max) | polars collect | polars sort-by a"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_string("one"), Value::test_string("two")], ), Column::new( "b".to_string(), vec![Value::test_int(4), Value::test_int(1)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_lazy(plugin, engine, call, df.lazy()), PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { NuExpression::from(expr.into_polars().max()).to_pipeline_data(plugin, engine, call.head) } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let res: NuLazyFrame = lazy.to_polars().max().into(); res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; use nu_protocol::ShellError; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ExprMax) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/min.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/min.rs
use crate::PolarsPlugin; use crate::dataframe::values::NuExpression; use crate::values::{ Column, CustomValueSupport, NuDataFrame, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; pub struct ExprMin; impl PluginCommand for ExprMin { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars min" } fn description(&self) -> &str { "Creates a min expression or aggregates columns to their min value." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Min value from columns in a dataframe", example: "[[a b]; [6 2] [1 4] [4 1]] | polars into-df | polars min", result: Some( NuDataFrame::try_from_columns( vec![ Column::new("a".to_string(), vec![Value::test_int(1)]), Column::new("b".to_string(), vec![Value::test_int(1)]), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Min aggregation for a group-by", example: r#"[[a b]; [one 2] [one 4] [two 1]] | polars into-df | polars group-by a | polars agg (polars col b | polars min) | polars collect | polars sort-by a"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_string("one"), Value::test_string("two")], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(1)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_lazy(plugin, engine, call, df.lazy()), PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { NuExpression::from(expr.into_polars().min()).to_pipeline_data(plugin, engine, call.head) } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let res: NuLazyFrame = lazy.to_polars().min().into(); res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; use nu_protocol::ShellError; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ExprMin) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/over.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/over.rs
use crate::{ PolarsPlugin, dataframe::values::{NuDataFrame, NuExpression}, values::{CustomValueSupport, PolarsPluginObject, PolarsPluginType, cant_convert_err}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::df; #[derive(Clone)] pub struct Over; impl PluginCommand for Over { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars over" } fn description(&self) -> &str { "Compute expressions over a window group defined by partition expressions." } fn signature(&self) -> Signature { Signature::build(self.name()) .rest( "partition by expressions", SyntaxShape::Any, "Expression(s) that define the partition window", ) .input_output_type( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Compute expression over an aggregation window", example: r#"[[a b]; [x 2] [x 4] [y 6] [y 4]] | polars into-lazy | polars select a (polars col b | polars cumulative sum | polars over a | polars as cum_b) | polars collect"#, result: Some( NuDataFrame::from( df!( "a" => &["x", "x", "y", "y"], "cum_b" => &[2, 6, 6, 10] ) .expect("should not fail"), ) .into_value(Span::test_data()), ), }, Example { description: "Compute expression over an aggregation window where partitions are defined by expressions", example: r#"[[a b]; [x 2] [X 4] [Y 6] [y 4]] | polars into-lazy | polars select a (polars col b | polars cumulative sum | polars over (polars col a | polars lowercase) | polars as cum_b) | polars collect"#, result: Some( NuDataFrame::from( df!( "a" => &["x", "X", "Y", "y"], "cum_b" => &[2, 6, 6, 10] ) .expect("should not fail"), ) .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let vals: Vec<Value> = call.rest(0)?; let expr_value = Value::list(vals, call.head); let expressions = NuExpression::extract_exprs(plugin, expr_value)?; let input_value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &input_value)? { PolarsPluginObject::NuExpression(expr) => { let expr: NuExpression = expr .into_polars() .over_with_options(Some(expressions), None, Default::default()) .map_err(|e| ShellError::GenericError { error: format!("Error applying over expression: {e}"), msg: "".into(), span: Some(call.head), help: None, inner: vec![], })? .into(); expr.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &input_value, &[PolarsPluginType::NuExpression], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; use nu_protocol::ShellError; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&Over) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/mod.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/mod.rs
mod agg_groups; mod aggregate; mod count; mod cumulative; pub mod groupby; mod horizontal; mod implode; mod max; mod mean; mod median; mod min; mod n_null; mod n_unique; mod over; mod quantile; mod rolling; mod std; mod sum; mod value_counts; mod var; use crate::PolarsPlugin; use agg_groups::ExprAggGroups; use nu_plugin::PluginCommand; pub use aggregate::LazyAggregate; use count::ExprCount; pub use cumulative::Cumulative; pub use horizontal::Horizontal; use implode::ExprImplode; use max::ExprMax; use mean::ExprMean; use min::ExprMin; pub use n_null::NNull; pub use n_unique::NUnique; pub use over::Over; pub use rolling::Rolling; use std::ExprStd; pub use sum::ExprSum; pub use value_counts::ValueCount; use var::ExprVar; pub(crate) fn aggregation_commands() -> Vec<Box<dyn PluginCommand<Plugin = PolarsPlugin>>> { vec![ Box::new(Cumulative), Box::new(ExprAggGroups), Box::new(ExprCount), Box::new(ExprImplode), Box::new(ExprMax), Box::new(ExprMean), Box::new(ExprMin), Box::new(ExprStd), Box::new(ExprSum), Box::new(ExprVar), Box::new(Horizontal), Box::new(LazyAggregate), Box::new(NNull), Box::new(NUnique), Box::new(Over), Box::new(Rolling), Box::new(ValueCount), Box::new(groupby::ToLazyGroupBy), Box::new(median::LazyMedian), Box::new(quantile::LazyQuantile), ] }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/implode.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/implode.rs
use crate::PolarsPlugin; use crate::dataframe::values::NuExpression; use crate::values::{ CustomValueSupport, NuDataFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, ShellError, Signature, Span}; use polars::df; use polars::series::Series; pub struct ExprImplode; impl PluginCommand for ExprImplode { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars implode" } fn description(&self) -> &str { "Aggregates values into a list." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Create two lists for columns a and b with all the rows as values.", example: "[[a b]; [1 4] [2 5] [3 6]] | polars into-df | polars select (polars col '*' | polars implode) | polars collect", result: Some( NuDataFrame::from( df!( "a"=> [[1i64, 2, 3].iter().collect::<Series>()], "b"=> [[4i64, 5, 6].iter().collect::<Series>()], ) .expect("should not fail"), ) .into_value(Span::unknown()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err(&value, &[PolarsPluginType::NuExpression])), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let res: NuExpression = expr.into_polars().implode().into(); res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; use nu_protocol::ShellError; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ExprImplode) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/value_counts.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/value_counts.rs
use crate::PolarsPlugin; use crate::values::{CustomValueSupport, NuDataFrame, PolarsPluginType}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, }; use polars::df; use polars::prelude::SeriesMethods; #[derive(Clone)] pub struct ValueCount; impl PluginCommand for ValueCount { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars value-counts" } fn description(&self) -> &str { "Returns a dataframe with the counts for unique values in series." } fn signature(&self) -> Signature { Signature::build(self.name()) .named( "column", SyntaxShape::String, "Provide a custom name for the count column", Some('c'), ) .switch("sort", "Whether or not values should be sorted", Some('s')) .switch( "parallel", "Use multiple threads when processing", Some('p'), ) .named( "normalize", SyntaxShape::String, "Normalize the counts", Some('n'), ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Calculates value counts", example: "[5 5 5 5 6 6] | polars into-df | polars value-counts | polars sort-by count", result: Some( NuDataFrame::from( df!( "0" => &[6i64, 5], "count" => &[2i64, 4], ) .expect("should not fail"), ) .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let column = call.get_flag("column")?.unwrap_or("count".to_string()); let parallel = call.has_flag("parallel")?; let sort = call.has_flag("sort")?; let normalize = call.has_flag("normalize")?; let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let series = df.as_series(call.head)?; let res = series .value_counts(sort, parallel, column.into(), normalize) .map_err(|e| ShellError::GenericError { error: "Error calculating value counts values".into(), msg: e.to_string(), span: Some(call.head), help: Some("The str-slice command can only be used with string columns".into()), inner: vec![], })?; let df: NuDataFrame = res.into(); df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ValueCount) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/n_null.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/n_null.rs
use crate::{PolarsPlugin, values::CustomValueSupport}; use crate::values::{Column, NuDataFrame, PolarsPluginType}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; #[derive(Clone)] pub struct NNull; impl PluginCommand for NNull { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars count-null" } fn description(&self) -> &str { "Counts null values." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Counts null values", example: r#"let s = ([1 1 0 0 3 3 4] | polars into-df); ($s / $s) | polars count-null"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "count_null".to_string(), vec![Value::test_int(2)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let res = df.as_series(call.head)?.null_count(); let value = Value::int(res as i64, call.head); let df = NuDataFrame::try_from_columns( vec![Column::new("count_null".to_string(), vec![value])], None, )?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&NNull) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/mean.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/mean.rs
use crate::PolarsPlugin; use crate::dataframe::values::NuExpression; use crate::values::{ Column, CustomValueSupport, NuDataFrame, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; pub struct ExprMean; impl PluginCommand for ExprMean { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars mean" } fn description(&self) -> &str { "Creates a mean expression for an aggregation or aggregates columns to their mean value." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Mean value from columns in a dataframe", example: "[[a b]; [6 2] [4 2] [2 2]] | polars into-df | polars mean", result: Some( NuDataFrame::try_from_columns( vec![ Column::new("a".to_string(), vec![Value::test_float(4.0)]), Column::new("b".to_string(), vec![Value::test_float(2.0)]), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Mean aggregation for a group-by", example: r#"[[a b]; [one 2] [one 4] [two 1]] | polars into-df | polars group-by a | polars agg (polars col b | polars mean) | polars collect | polars sort-by a"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_string("one"), Value::test_string("two")], ), Column::new( "b".to_string(), vec![Value::test_float(3.0), Value::test_float(1.0)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_lazy(plugin, engine, call, df.lazy()), PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { NuExpression::from(expr.into_polars().mean()).to_pipeline_data(plugin, engine, call.head) } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let res: NuLazyFrame = lazy.to_polars().mean().into(); res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; use nu_protocol::ShellError; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ExprMean) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/std.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/std.rs
use crate::PolarsPlugin; use crate::values::{ Column, CustomValueSupport, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }; use crate::{dataframe::values::NuExpression, values::NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; use polars::df; pub struct ExprStd; impl PluginCommand for ExprStd { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars std" } fn description(&self) -> &str { "Creates a std expression for an aggregation of std value from columns in a dataframe." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Std value from columns in a dataframe", example: "[[a b]; [6 2] [4 2] [2 2]] | polars into-df | polars std | polars collect", result: Some( NuDataFrame::try_from_columns( vec![ Column::new("a".to_string(), vec![Value::test_float(2.0)]), Column::new("b".to_string(), vec![Value::test_float(0.0)]), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Std aggregation for a group-by", example: r#"[[a b]; [one 2] [one 2] [two 1] [two 1]] | polars into-df | polars group-by a | polars agg (polars col b | polars std) | polars collect | polars sort-by a"#, result: Some( NuDataFrame::from( df!( "a" => &["one", "two"], "b" => &[0.0f64, 0.0], ) .expect("should not fail"), ) .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_lazy(plugin, engine, call, df.lazy()), PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { NuExpression::from(expr.into_polars().std(1)).to_pipeline_data(plugin, engine, call.head) } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let res: NuLazyFrame = lazy.to_polars().std(1).into(); res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ExprStd) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/aggregate.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/aggregate.rs
use crate::{ PolarsPlugin, dataframe::values::{NuExpression, NuLazyFrame, NuLazyGroupBy}, values::{Column, CustomValueSupport, NuDataFrame, PolarsPluginType}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::{datatypes::DataType, prelude::Expr}; #[derive(Clone)] pub struct LazyAggregate; impl PluginCommand for LazyAggregate { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars agg" } fn description(&self) -> &str { "Performs a series of aggregations from a group-by." } fn signature(&self) -> Signature { Signature::build(self.name()) .rest( "Group-by expressions", SyntaxShape::Any, "Expression(s) that define the aggregations to be applied", ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Group by and perform an aggregation", example: r#"[[a b]; [1 2] [1 4] [2 6] [2 4]] | polars into-lazy | polars group-by a | polars agg [ (polars col b | polars min | polars as "b_min") (polars col b | polars max | polars as "b_max") (polars col b | polars sum | polars as "b_sum") ] | polars collect | polars sort-by a"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(2)], ), Column::new( "b_min".to_string(), vec![Value::test_int(2), Value::test_int(4)], ), Column::new( "b_max".to_string(), vec![Value::test_int(4), Value::test_int(6)], ), Column::new( "b_sum".to_string(), vec![Value::test_int(6), Value::test_int(10)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Group by and perform an aggregation using a record", example: r#"[[a b]; [1 2] [1 4] [2 6] [2 4]] | polars into-lazy | polars group-by a | polars agg { b_min: (polars col b | polars min) b_max: (polars col b | polars max) b_sum: (polars col b | polars sum) } | polars collect | polars sort-by a"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(2)], ), Column::new( "b_min".to_string(), vec![Value::test_int(2), Value::test_int(4)], ), Column::new( "b_max".to_string(), vec![Value::test_int(4), Value::test_int(6)], ), Column::new( "b_sum".to_string(), vec![Value::test_int(6), Value::test_int(10)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let vals: Vec<Value> = call.rest(0)?; let value = Value::list(vals, call.head); let expressions = NuExpression::extract_exprs(plugin, value)?; let group_by = NuLazyGroupBy::try_from_pipeline(plugin, input, call.head)?; for expr in expressions.iter() { if let Some(name) = get_col_name(expr) { let dtype = group_by.schema.schema.get(name.as_str()); if let Some(DataType::Object(..)) = dtype { return Err(ShellError::GenericError { error: "Object type column not supported for aggregation".into(), msg: format!("Column '{name}' is type Object"), span: Some(call.head), help: Some("Aggregations cannot be performed on Object type columns. Use dtype command to check column types".into()), inner: vec![], }).map_err(|e| e.into()); } } } let polars = group_by.to_polars(); let lazy = NuLazyFrame::new(false, polars.agg(&expressions)); lazy.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn get_col_name(expr: &Expr) -> Option<String> { match expr { Expr::Column(column) => Some(column.to_string()), Expr::Agg(agg) => match agg { polars::prelude::AggExpr::Min { input: e, .. } | polars::prelude::AggExpr::Max { input: e, .. } | polars::prelude::AggExpr::Median(e) | polars::prelude::AggExpr::NUnique(e) | polars::prelude::AggExpr::First(e) | polars::prelude::AggExpr::Last(e) | polars::prelude::AggExpr::Mean(e) | polars::prelude::AggExpr::Implode(e) | polars::prelude::AggExpr::Count { input: e, .. } | polars::prelude::AggExpr::Sum(e) | polars::prelude::AggExpr::AggGroups(e) | polars::prelude::AggExpr::Std(e, _) | polars::prelude::AggExpr::Var(e, _) | polars::prelude::AggExpr::Item { input: e, .. } | polars::prelude::AggExpr::Quantile { expr: e, .. } => get_col_name(e.as_ref()), }, Expr::Filter { input: expr, .. } | Expr::Slice { input: expr, .. } | Expr::Cast { expr, .. } | Expr::Sort { expr, .. } | Expr::Gather { expr, .. } | Expr::SortBy { expr, .. } | Expr::KeepName(expr) | Expr::Explode { input: expr, .. } => get_col_name(expr.as_ref()), Expr::Ternary { .. } | Expr::AnonymousFunction { .. } | Expr::Function { .. } | Expr::Literal(_) | Expr::BinaryExpr { .. } | Expr::Window { .. } | Expr::RenameAlias { .. } | Expr::Len | Expr::SubPlan(_, _) | Expr::Selector(_) | Expr::Field(_) | Expr::Alias(_, _) | Expr::DataTypeFunction(_) | Expr::Element | Expr::Eval { .. } => None, } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&LazyAggregate) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/agg_groups.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/agg_groups.rs
use crate::PolarsPlugin; use crate::dataframe::values::NuExpression; use crate::values::{ CustomValueSupport, NuDataFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, ShellError, Signature, Span}; use polars::df; use polars::series::Series; pub struct ExprAggGroups; impl PluginCommand for ExprAggGroups { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars agg-groups" } fn description(&self) -> &str { "Creates an agg_groups expression." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), )]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Get the group index of the group by operations.", example: r#"[[group value]; [one 94] [one 95] [one 96] [two 97] [two 98] [two 99]] | polars into-df | polars group-by group | polars agg (polars col value | polars agg-groups) | polars collect | polars sort-by group"#, result: Some( NuDataFrame::from( df!( "group"=> ["one", "two"], "values" => [[0i64, 1, 2].iter().collect::<Series>(), [3i64, 4, 5].iter().collect::<Series>()], ) .expect("should not fail"), ) .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err(&value, &[PolarsPluginType::NuExpression])), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { NuExpression::from(expr.into_polars().agg_groups()).to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; use nu_protocol::ShellError; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ExprAggGroups) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/n_unique.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/n_unique.rs
use crate::{ PolarsPlugin, values::{CustomValueSupport, PolarsPluginObject, PolarsPluginType, cant_convert_err}, }; use crate::values::{Column, NuDataFrame, NuExpression}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; #[derive(Clone)] pub struct NUnique; impl PluginCommand for NUnique { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars n-unique" } fn description(&self) -> &str { "Counts unique values." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Counts unique values", example: "[1 1 2 2 3 3 4] | polars into-df | polars n-unique", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "count_unique".to_string(), vec![Value::test_int(4)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Creates a is n-unique expression from a column", example: "polars col a | polars n-unique", result: None, }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => { command(plugin, engine, call, lazy.collect(call.head)?) } PolarsPluginObject::NuExpression(expr) => { let expr: NuExpression = expr.into_polars().n_unique().into(); expr.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let res = df .as_series(call.head)? .n_unique() .map_err(|e| ShellError::GenericError { error: "Error counting unique values".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let value = Value::int(res as i64, call.head); let df = NuDataFrame::try_from_columns( vec![Column::new("count_unique".to_string(), vec![value])], None, )?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&NUnique) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/var.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/var.rs
use crate::PolarsPlugin; use crate::dataframe::values::NuExpression; use crate::values::{ Column, CustomValueSupport, NuDataFrame, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; use polars::df; pub struct ExprVar; impl PluginCommand for ExprVar { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars var" } fn description(&self) -> &str { "Create a var expression for an aggregation." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Var value from columns in a dataframe or aggregates columns to their var value", example: "[[a b]; [6 2] [4 2] [2 2]] | polars into-df | polars var | polars collect", result: Some( NuDataFrame::try_from_columns( vec![ Column::new("a".to_string(), vec![Value::test_float(4.0)]), Column::new("b".to_string(), vec![Value::test_float(0.0)]), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Var aggregation for a group-by", example: r#"[[a b]; [one 2] [one 2] [two 1] [two 1]] | polars into-df | polars group-by a | polars agg (polars col b | polars var) | polars collect | polars sort-by a"#, result: Some( NuDataFrame::from( df!( "a" => &["one", "two"], "b" => &[0.0, 0.0], ) .expect("should not fail"), ) .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_lazy(plugin, engine, call, df.lazy()), PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { NuExpression::from(expr.into_polars().var(1)).to_pipeline_data(plugin, engine, call.head) } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let res: NuLazyFrame = lazy.to_polars().var(1).into(); res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; use nu_protocol::ShellError; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ExprVar) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/aggregation/rolling.rs
crates/nu_plugin_polars/src/dataframe/command/aggregation/rolling.rs
use crate::values::{Column, NuDataFrame, PolarsPluginType}; use crate::{PolarsPlugin, values::CustomValueSupport}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Value, }; use polars::prelude::{DataType, IntoSeries, RollingOptionsFixedWindow, SeriesOpsTime}; enum RollType { Min, Max, Sum, Mean, } impl RollType { fn from_str(roll_type: &str, span: Span) -> Result<Self, ShellError> { match roll_type { "min" => Ok(Self::Min), "max" => Ok(Self::Max), "sum" => Ok(Self::Sum), "mean" => Ok(Self::Mean), _ => Err(ShellError::GenericError { error: "Wrong operation".into(), msg: "Operation not valid for cumulative".into(), span: Some(span), help: Some("Allowed values: min, max, sum, mean".into()), inner: vec![], }), } } fn to_str(&self) -> &'static str { match self { RollType::Min => "rolling_min", RollType::Max => "rolling_max", RollType::Sum => "rolling_sum", RollType::Mean => "rolling_mean", } } } #[derive(Clone)] pub struct Rolling; impl PluginCommand for Rolling { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars rolling" } fn description(&self) -> &str { "Rolling calculation for a series." } fn signature(&self) -> Signature { Signature::build(self.name()) .required("type", SyntaxShape::String, "rolling operation") .required("window", SyntaxShape::Int, "Window size for rolling") .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Rolling sum for a series", example: "[1 2 3 4 5] | polars into-df | polars rolling sum 2 | polars drop-nulls", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0_rolling_sum".to_string(), vec![ Value::test_int(3), Value::test_int(5), Value::test_int(7), Value::test_int(9), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Rolling max for a series", example: "[1 2 3 4 5] | polars into-df | polars rolling max 2 | polars drop-nulls", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0_rolling_max".to_string(), vec![ Value::test_int(2), Value::test_int(3), Value::test_int(4), Value::test_int(5), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> 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() { return Err(ShellError::GenericError { error: "Found object series".into(), msg: "Series of type object cannot be used for rolling operation".into(), span: Some(call.head), help: None, inner: vec![], }); } let roll_type = RollType::from_str(&roll_type.item, roll_type.span)?; let rolling_opts = RollingOptionsFixedWindow { window_size, min_periods: window_size, ..RollingOptionsFixedWindow::default() }; let res = match roll_type { RollType::Max => series.rolling_max(rolling_opts), RollType::Min => series.rolling_min(rolling_opts), RollType::Sum => series.rolling_sum(rolling_opts), RollType::Mean => series.rolling_mean(rolling_opts), }; let mut res = res.map_err(|e| ShellError::GenericError { error: "Error calculating rolling values".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let name = format!("{}_{}", series.name(), roll_type.to_str()); res.rename(name.into()); let df = NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&Rolling) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/open.rs
crates/nu_plugin_polars/src/dataframe/command/core/open.rs
use crate::{ EngineWrapper, PolarsPlugin, command::core::resource::Resource, dataframe::values::NuSchema, values::{CustomValueSupport, NuDataFrame, NuLazyFrame, PolarsFileType, PolarsPluginType}, }; use log::debug; use nu_utils::perf; use nu_plugin::{EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, DataSource, Example, LabeledError, PipelineData, PipelineMetadata, ShellError, Signature, Span, Spanned, SyntaxShape, Type, Value, shell_error::{self, io::IoError}, }; use std::{fs::File, io::BufReader, num::NonZeroUsize, path::PathBuf, sync::Arc}; use polars::{ lazy::frame::LazyJsonLineReader, prelude::{ CsvEncoding, IpcReader, JsonFormat, JsonReader, LazyCsvReader, LazyFileListReader, LazyFrame, ParquetReader, PlSmallStr, ScanArgsParquet, SerReader, UnifiedScanArgs, }, }; use polars_io::{HiveOptions, avro::AvroReader, csv::read::CsvReadOptions, ipc::IpcScanOptions}; const DEFAULT_INFER_SCHEMA: usize = 100; #[derive(Clone)] pub struct OpenDataFrame; impl PluginCommand for OpenDataFrame { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars open" } fn description(&self) -> &str { "Opens CSV, JSON, NDJSON/JSON lines, arrow, avro, or parquet file to create dataframe. A lazy dataframe will be created by default, if supported." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "file", SyntaxShape::String, "file path or cloud url to load values from", ) .switch("eager", "Open dataframe as an eager dataframe", None) .named( "type", SyntaxShape::String, "File type: csv, tsv, json, parquet, arrow, avro. If omitted, derive from file extension", Some('t'), ) .named( "delimiter", SyntaxShape::String, "file delimiter character. CSV file", Some('d'), ) .switch( "no-header", "Indicates if file doesn't have header. CSV file", None, ) .named( "infer-schema", SyntaxShape::Number, "Number of rows to infer the schema of the file. CSV file", None, ) .named( "skip-rows", SyntaxShape::Number, "Number of rows to skip from file. CSV file", None, ) .named( "columns", SyntaxShape::List(Box::new(SyntaxShape::String)), "Columns to be selected from csv file. CSV and Parquet file", None, ) .named( "schema", SyntaxShape::Any, r#"Polars Schema in format [{name: str}]. CSV, JSON, and JSONL files"#, Some('s') ) .switch( "hive-enabled", "Enable hive support. Parquet and Arrow files", None, ) .named( "hive-start-idx", SyntaxShape::Number, "Start index of hive partitioning. Parquet and Arrow files", None, ) .named( "hive-schema", SyntaxShape::Any, r#"Hive schema in format [{name: str}]. Parquet and Arrow files"#, None, ) .switch( "hive-try-parse-dates", "Try to parse dates in hive partitioning. Parquet and Arrow files", None, ) .switch("truncate-ragged-lines", "Truncate lines that are longer than the schema. CSV file", None) .input_output_types(vec![ ( Type::Any, PolarsPluginType::NuDataFrame.into(), ), ( Type::Any, PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Takes a file name and creates a dataframe", example: "polars open test.csv", result: None, }] } fn run( &self, plugin: &Self::Plugin, engine: &nu_plugin::EngineInterface, call: &nu_plugin::EvaluatedCall, _input: PipelineData, ) -> Result<PipelineData, LabeledError> { command(plugin, engine, call).map_err(|e| e.into()) } } fn command( plugin: &PolarsPlugin, engine: &nu_plugin::EngineInterface, call: &nu_plugin::EvaluatedCall, ) -> Result<PipelineData, ShellError> { let spanned_file: Spanned<String> = call.req(0)?; debug!("file: {}", spanned_file.item); let resource = Resource::new(plugin, engine, &spanned_file)?; let type_option: Option<(String, Span)> = call .get_flag("type")? .map(|t: Spanned<String>| (t.item, t.span)) .or_else(|| { resource .path .as_ref() .extension() .map(|e| (e.to_string(), resource.span)) }); debug!("resource: {resource:?}"); let is_eager = call.has_flag("eager")?; if is_eager && resource.cloud_options.is_some() { return Err(ShellError::GenericError { error: "Cloud URLs are not supported with --eager".into(), msg: "".into(), span: call.get_flag_span("eager"), help: Some("Remove flag".into()), inner: vec![], }); } let hive_options = build_hive_options(plugin, call)?; let uri = spanned_file.item.clone(); let data_source = DataSource::FilePath(uri.into()); let metadata = PipelineMetadata::default().with_data_source(data_source); match type_option { Some((ext, blamed)) => match PolarsFileType::from(ext.as_str()) { file_type @ (PolarsFileType::Csv | PolarsFileType::Tsv) => { from_csv(plugin, engine, call, file_type, resource, is_eager) } PolarsFileType::Parquet => { from_parquet(plugin, engine, call, resource, is_eager, hive_options) } PolarsFileType::Arrow => { from_arrow(plugin, engine, call, resource, is_eager, hive_options) } PolarsFileType::Json => from_json(plugin, engine, call, resource, is_eager), PolarsFileType::NdJson => from_ndjson(plugin, engine, call, resource, is_eager), PolarsFileType::Avro => from_avro(plugin, engine, call, resource, is_eager), _ => Err(PolarsFileType::build_unsupported_error( &ext, &[ PolarsFileType::Csv, PolarsFileType::Tsv, PolarsFileType::Parquet, PolarsFileType::Arrow, PolarsFileType::NdJson, PolarsFileType::Avro, ], blamed, )), }, None => Err(ShellError::Io(IoError::new_with_additional_context( shell_error::io::ErrorKind::from_std(std::io::ErrorKind::Other), spanned_file.span, PathBuf::from(spanned_file.item), "File without extension", ))), } .map(|value| PipelineData::value(value, Some(metadata))) } fn from_parquet( plugin: &PolarsPlugin, engine: &nu_plugin::EngineInterface, call: &nu_plugin::EvaluatedCall, resource: Resource, is_eager: bool, hive_options: HiveOptions, ) -> Result<Value, ShellError> { if !is_eager { let args = ScanArgsParquet { cloud_options: resource.cloud_options, hive_options, ..Default::default() }; let df: NuLazyFrame = LazyFrame::scan_parquet(resource.path, args) .map_err(|e| ShellError::GenericError { error: "Parquet reader error".into(), msg: format!("{e:?}"), span: Some(call.head), help: None, inner: vec![], })? .into(); df.cache_and_to_value(plugin, engine, call.head) } else { let columns: Option<Vec<String>> = call.get_flag("columns")?; let file_span = resource.span; let path: PathBuf = resource.try_into()?; let r = File::open(&path).map_err(|e| ShellError::GenericError { error: "Error opening file".into(), msg: e.to_string(), span: Some(file_span), help: None, inner: vec![], })?; let reader = ParquetReader::new(r); let reader = match columns { None => reader, Some(columns) => reader.with_columns(Some(columns)), }; let df: NuDataFrame = reader .finish() .map_err(|e| ShellError::GenericError { error: "Parquet reader error".into(), msg: format!("{e:?}"), span: Some(call.head), help: None, inner: vec![], })? .into(); df.cache_and_to_value(plugin, engine, call.head) } } fn from_avro( plugin: &PolarsPlugin, engine: &nu_plugin::EngineInterface, call: &nu_plugin::EvaluatedCall, resource: Resource, _is_eager: bool, // ignore, lazy frames are not currently supported ) -> Result<Value, ShellError> { if resource.cloud_options.is_some() { return Err(cloud_not_supported(PolarsFileType::Avro, resource.span)); } let columns: Option<Vec<String>> = call.get_flag("columns")?; let file_span = resource.span; let path: PathBuf = resource.try_into()?; let r = File::open(&path).map_err(|e| ShellError::GenericError { error: "Error opening file".into(), msg: e.to_string(), span: Some(file_span), help: None, inner: vec![], })?; let reader = AvroReader::new(r); let reader = match columns { None => reader, Some(columns) => reader.with_columns(Some(columns)), }; let df: NuDataFrame = reader .finish() .map_err(|e| ShellError::GenericError { error: "Avro reader error".into(), msg: format!("{e:?}"), span: Some(call.head), help: None, inner: vec![], })? .into(); df.cache_and_to_value(plugin, engine, call.head) } fn from_arrow( plugin: &PolarsPlugin, engine: &nu_plugin::EngineInterface, call: &nu_plugin::EvaluatedCall, resource: Resource, is_eager: bool, hive_options: HiveOptions, ) -> Result<Value, ShellError> { if !is_eager { let args = UnifiedScanArgs { cache: true, rechunk: false, row_index: None, cloud_options: resource.cloud_options, include_file_paths: None, hive_options, ..Default::default() }; let df: NuLazyFrame = LazyFrame::scan_ipc(resource.path, IpcScanOptions, args) .map_err(|e| ShellError::GenericError { error: "IPC reader error".into(), msg: format!("{e:?}"), span: Some(call.head), help: None, inner: vec![], })? .into(); df.cache_and_to_value(plugin, engine, call.head) } else { let columns: Option<Vec<String>> = call.get_flag("columns")?; let file_span = resource.span; let path: PathBuf = resource.try_into()?; let r = File::open(&path).map_err(|e| ShellError::GenericError { error: "Error opening file".into(), msg: e.to_string(), span: Some(file_span), help: None, inner: vec![], })?; let reader = IpcReader::new(r); let reader = match columns { None => reader, Some(columns) => reader.with_columns(Some(columns)), }; let df: NuDataFrame = reader .finish() .map_err(|e| ShellError::GenericError { error: "IPC reader error".into(), msg: format!("{e:?}"), span: Some(call.head), help: None, inner: vec![], })? .into(); df.cache_and_to_value(plugin, engine, call.head) } } fn from_json( plugin: &PolarsPlugin, engine: &nu_plugin::EngineInterface, call: &nu_plugin::EvaluatedCall, resource: Resource, _is_eager: bool, // ignore = lazy frames not currently supported ) -> Result<Value, ShellError> { let file_span = resource.span; if resource.cloud_options.is_some() { return Err(cloud_not_supported(PolarsFileType::Json, file_span)); } let path: PathBuf = resource.try_into()?; let file = File::open(&path).map_err(|e| ShellError::GenericError { error: "Error opening file".into(), msg: e.to_string(), span: Some(file_span), help: None, inner: vec![], })?; let maybe_schema = call .get_flag("schema")? .map(|schema| NuSchema::try_from_value(plugin, &schema)) .transpose()?; let buf_reader = BufReader::new(file); let reader = JsonReader::new(buf_reader); let reader = match maybe_schema { Some(schema) => reader.with_schema(schema.into()), None => reader, }; let df: NuDataFrame = reader .finish() .map_err(|e| ShellError::GenericError { error: "Json reader error".into(), msg: format!("{e:?}"), span: Some(call.head), help: None, inner: vec![], })? .into(); df.cache_and_to_value(plugin, engine, call.head) } fn from_ndjson( plugin: &PolarsPlugin, engine: &nu_plugin::EngineInterface, call: &nu_plugin::EvaluatedCall, resource: Resource, is_eager: bool, ) -> Result<Value, ShellError> { let infer_schema: NonZeroUsize = call .get_flag("infer-schema")? .and_then(NonZeroUsize::new) .unwrap_or( NonZeroUsize::new(DEFAULT_INFER_SCHEMA) .expect("The default infer-schema should be non zero"), ); let maybe_schema = get_schema(plugin, call)?; if !is_eager { let start_time = std::time::Instant::now(); let df = LazyJsonLineReader::new(resource.path) .with_infer_schema_length(Some(infer_schema)) .with_schema(maybe_schema.map(|s| s.into())) .with_cloud_options(resource.cloud_options.clone()) .finish() .map_err(|e| ShellError::GenericError { error: format!("NDJSON reader error: {e}"), msg: "".into(), span: Some(call.head), help: None, inner: vec![], })?; perf!("Lazy NDJSON dataframe open", start_time, engine.use_color()); let df = NuLazyFrame::new(false, df); df.cache_and_to_value(plugin, engine, call.head) } else { let file_span = resource.span; let path: PathBuf = resource.try_into()?; let file = File::open(&path).map_err(|e| ShellError::GenericError { error: "Error opening file".into(), msg: e.to_string(), span: Some(file_span), help: None, inner: vec![], })?; let buf_reader = BufReader::new(file); let reader = JsonReader::new(buf_reader) .with_json_format(JsonFormat::JsonLines) .infer_schema_len(Some(infer_schema)); let reader = match maybe_schema { Some(schema) => reader.with_schema(schema.into()), None => reader, }; let start_time = std::time::Instant::now(); let df: NuDataFrame = reader .finish() .map_err(|e| ShellError::GenericError { error: "Json lines reader error".into(), msg: format!("{e:?}"), span: Some(call.head), help: None, inner: vec![], })? .into(); perf!( "Eager NDJSON dataframe open", start_time, engine.use_color() ); df.cache_and_to_value(plugin, engine, call.head) } } fn from_csv( plugin: &PolarsPlugin, engine: &nu_plugin::EngineInterface, call: &nu_plugin::EvaluatedCall, file_type: PolarsFileType, resource: Resource, is_eager: bool, ) -> Result<Value, ShellError> { let delimiter: Option<Spanned<String>> = call.get_flag("delimiter")?; let no_header: bool = call.has_flag("no-header")?; let infer_schema: usize = call .get_flag("infer-schema")? .unwrap_or(DEFAULT_INFER_SCHEMA); let skip_rows: Option<usize> = call.get_flag("skip-rows")?; let columns: Option<Vec<String>> = call.get_flag("columns")?; let maybe_schema = get_schema(plugin, call)?; let truncate_ragged_lines: bool = call.has_flag("truncate-ragged-lines")?; if !is_eager { let csv_reader = LazyCsvReader::new(resource.path).with_cloud_options(resource.cloud_options); let csv_reader = match delimiter { None => match file_type { PolarsFileType::Tsv => csv_reader.with_separator(b'\t'), _ => csv_reader, }, Some(d) => { if d.item.len() != 1 { return Err(ShellError::GenericError { error: "Incorrect delimiter".into(), msg: "Delimiter has to be one character".into(), span: Some(d.span), help: None, inner: vec![], }); } else { let delimiter = match d.item.chars().next() { Some(d) => d as u8, None => unreachable!(), }; csv_reader.with_separator(delimiter) } } }; let csv_reader = csv_reader .with_has_header(!no_header) .with_infer_schema_length(Some(infer_schema)) .with_schema(maybe_schema.map(Into::into)) .with_truncate_ragged_lines(truncate_ragged_lines); let csv_reader = match skip_rows { None => csv_reader, Some(r) => csv_reader.with_skip_rows(r), }; let start_time = std::time::Instant::now(); let df: NuLazyFrame = csv_reader .finish() .map_err(|e| ShellError::GenericError { error: "CSV reader error".into(), msg: format!("{e:?}"), span: Some(call.head), help: None, inner: vec![], })? .into(); perf!("Lazy CSV dataframe open", start_time, engine.use_color()); df.cache_and_to_value(plugin, engine, call.head) } else { let file_span = resource.span; let start_time = std::time::Instant::now(); let df = CsvReadOptions::default() .with_has_header(!no_header) .with_infer_schema_length(Some(infer_schema)) .with_skip_rows(skip_rows.unwrap_or_default()) .with_schema(maybe_schema.map(|s| s.into())) .with_columns( columns .map(|v| v.iter().map(PlSmallStr::from).collect::<Vec<PlSmallStr>>()) .map(|v| Arc::from(v.into_boxed_slice())), ) .map_parse_options(|options| { options .with_separator( delimiter .as_ref() .and_then(|d| d.item.chars().next().map(|c| c as u8)) .unwrap_or(b','), ) .with_encoding(CsvEncoding::LossyUtf8) .with_truncate_ragged_lines(truncate_ragged_lines) }) .try_into_reader_with_file_path(Some(resource.try_into()?)) .map_err(|e| ShellError::GenericError { error: "Error creating CSV reader".into(), msg: e.to_string(), span: Some(file_span), help: None, inner: vec![], })? .finish() .map_err(|e| ShellError::GenericError { error: "CSV reader error".into(), msg: format!("{e:?}"), span: Some(call.head), help: None, inner: vec![], })?; perf!("Eager CSV dataframe open", start_time, engine.use_color()); let df = NuDataFrame::new(false, df); df.cache_and_to_value(plugin, engine, call.head) } } fn cloud_not_supported(file_type: PolarsFileType, span: Span) -> ShellError { ShellError::GenericError { error: format!( "Cloud operations not supported for file type {}", file_type.to_str() ), msg: "".into(), span: Some(span), help: None, inner: vec![], } } fn build_hive_options( plugin: &PolarsPlugin, call: &EvaluatedCall, ) -> Result<HiveOptions, ShellError> { let enabled: Option<bool> = call.get_flag("hive-enabled")?; let hive_start_idx: Option<usize> = call.get_flag("hive-start-idx")?; let schema: Option<NuSchema> = call .get_flag::<Value>("hive-schema")? .map(|schema| NuSchema::try_from_value(plugin, &schema)) .transpose()?; let try_parse_dates: bool = call.has_flag("hive-try-parse-dates")?; Ok(HiveOptions { enabled, hive_start_idx: hive_start_idx.unwrap_or(0), schema: schema.map(|s| s.into()), try_parse_dates, }) } fn get_schema(plugin: &PolarsPlugin, call: &EvaluatedCall) -> Result<Option<NuSchema>, ShellError> { let schema: Option<NuSchema> = call .get_flag("schema")? .map(|schema| NuSchema::try_from_value(plugin, &schema)) .transpose()?; Ok(schema) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/resource.rs
crates/nu_plugin_polars/src/dataframe/command/core/resource.rs
use std::path::PathBuf; use crate::{PolarsPlugin, cloud::build_cloud_options}; use nu_path::expand_path_with; use nu_plugin::EngineInterface; use nu_protocol::{ShellError, Span, Spanned}; use polars::{ io::cloud::CloudOptions, prelude::{PlPath, PlPathRef, SinkTarget}, }; #[derive(Clone)] pub(crate) struct Resource { pub(crate) path: PlPath, pub(crate) cloud_options: Option<CloudOptions>, pub(crate) span: Span, } impl std::fmt::Debug for Resource { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // We can't print out the cloud options as it might have // secrets in it.. So just print whether or not it was defined f.debug_struct("Resource") .field("path", &self.path) .field("has_cloud_options", &self.cloud_options.is_some()) .field("span", &self.span) .finish() } } impl Resource { pub(crate) fn new( plugin: &PolarsPlugin, engine: &EngineInterface, spanned_path: &Spanned<String>, ) -> Result<Self, ShellError> { let path = PlPath::from_str(&spanned_path.item); let (path, cloud_options): (PlPath, Option<CloudOptions>) = if path.is_cloud_url() { let options = build_cloud_options(plugin, &path)?; if options.is_none() { return Err(ShellError::GenericError { error: format!( "Could not determine a supported cloud type from path: {}", path.to_str() ), msg: "".into(), span: None, help: None, inner: vec![], }); } (path, options) } else { let new_path = expand_path_with(&spanned_path.item, engine.get_current_dir()?, true); (PlPathRef::from_local_path(&new_path).into_owned(), None) }; Ok(Self { path, cloud_options, span: spanned_path.span, }) } pub fn as_string(&self) -> String { self.path.to_str().to_owned() } } impl TryInto<PathBuf> for Resource { type Error = ShellError; fn try_into(self) -> Result<PathBuf, Self::Error> { let path_str = self.path.to_str().to_owned(); self.path .into_local_path() .ok_or_else(|| ShellError::GenericError { error: format!("Could not convert path to local path: {path_str}",), msg: "".into(), span: Some(self.span), help: None, inner: vec![], }) .map(|p| (*p).into()) } } impl From<Resource> for SinkTarget { fn from(r: Resource) -> SinkTarget { SinkTarget::Path(r.path) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/shape.rs
crates/nu_plugin_polars/src/dataframe/command/core/shape.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; use crate::{PolarsPlugin, dataframe::values::Column, values::CustomValueSupport}; use crate::values::{NuDataFrame, PolarsPluginType}; #[derive(Clone)] pub struct ShapeDF; impl PluginCommand for ShapeDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars shape" } fn description(&self) -> &str { "Shows column and row size for a dataframe." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Shows row and column shape", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars shape", result: Some( NuDataFrame::try_from_columns( vec![ Column::new("rows".to_string(), vec![Value::test_int(2)]), Column::new("columns".to_string(), vec![Value::test_int(2)]), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { command(plugin, engine, call, input).map_err(LabeledError::from) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let rows = Value::int(df.as_ref().height() as i64, call.head); let cols = Value::int(df.as_ref().width() as i64, call.head); let rows_col = Column::new("rows".to_string(), vec![rows]); let cols_col = Column::new("columns".to_string(), vec![cols]); let df = NuDataFrame::try_from_columns(vec![rows_col, cols_col], None)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ShapeDF) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/columns.rs
crates/nu_plugin_polars/src/dataframe/command/core/columns.rs
use crate::values::NuDataFrame; use crate::{PolarsPlugin, values::PolarsPluginType}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; #[derive(Clone)] pub struct ColumnsDF; impl PluginCommand for ColumnsDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars columns" } fn description(&self) -> &str { "Show dataframe columns." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Dataframe columns", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars columns", result: Some(Value::list( vec![Value::test_string("a"), Value::test_string("b")], Span::test_data(), )), }] } fn run( &self, plugin: &Self::Plugin, _engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, call, input) .map_err(|e| e.into()) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let names: Vec<Value> = df .as_ref() .get_column_names() .iter() .map(|v| Value::string(v.as_str(), call.head)) .collect(); let names = Value::list(names, call.head); Ok(PipelineData::value(names, None)) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ColumnsDF) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/to_schema.rs
crates/nu_plugin_polars/src/dataframe/command/core/to_schema.rs
use nu_plugin::PluginCommand; use nu_protocol::{Category, Example, ShellError, Signature, Span, Type, Value, record}; use crate::{ PolarsPlugin, values::{CustomValueSupport, NuSchema, PolarsPluginType}, }; pub struct ToSchema; impl PluginCommand for ToSchema { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars into-schema" } fn description(&self) -> &str { "Convert a value to a polars schema object" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type(Type::Any, PolarsPluginType::NuSchema.into()) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Convert a record into a schema and back to a nu object", example: r#"{a: str, b: u8} | polars into-schema | polars into-nu"#, result: Some(Value::record( record! { "a" => Value::string("str", Span::test_data()), "b" => Value::string("u8", Span::test_data()), }, Span::test_data(), )), }] } fn run( &self, plugin: &Self::Plugin, engine: &nu_plugin::EngineInterface, call: &nu_plugin::EvaluatedCall, input: nu_protocol::PipelineData, ) -> Result<nu_protocol::PipelineData, nu_protocol::LabeledError> { command(plugin, engine, call, input).map_err(nu_protocol::LabeledError::from) } } fn command( plugin: &PolarsPlugin, engine: &nu_plugin::EngineInterface, call: &nu_plugin::EvaluatedCall, input: nu_protocol::PipelineData, ) -> Result<nu_protocol::PipelineData, ShellError> { NuSchema::try_from_pipeline(plugin, input, call.head)? .to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; use nu_protocol::ShellError; #[test] fn test_into_schema() -> Result<(), ShellError> { test_polars_plugin_command(&ToSchema) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/to_dtype.rs
crates/nu_plugin_polars/src/dataframe/command/core/to_dtype.rs
use nu_plugin::PluginCommand; use nu_protocol::{Category, Example, ShellError, Signature, Span, Type, Value}; use crate::{ PolarsPlugin, values::{CustomValueSupport, NuDataType, PolarsPluginType}, }; pub struct ToDataType; impl PluginCommand for ToDataType { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars into-dtype" } fn description(&self) -> &str { "Convert a string to a specific datatype." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type(Type::String, PolarsPluginType::NuDataFrame.into()) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Convert a string to a specific datatype and back to a nu object", example: r#"'i64' | polars into-dtype | polars into-nu"#, result: Some(Value::string("i64", Span::test_data())), }] } fn run( &self, plugin: &Self::Plugin, engine: &nu_plugin::EngineInterface, call: &nu_plugin::EvaluatedCall, input: nu_protocol::PipelineData, ) -> Result<nu_protocol::PipelineData, nu_protocol::LabeledError> { command(plugin, engine, call, input).map_err(nu_protocol::LabeledError::from) } } fn command( plugin: &PolarsPlugin, engine: &nu_plugin::EngineInterface, call: &nu_plugin::EvaluatedCall, input: nu_protocol::PipelineData, ) -> Result<nu_protocol::PipelineData, ShellError> { NuDataType::try_from_pipeline(plugin, input, call.head)? .to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; use nu_protocol::ShellError; #[test] fn test_into_dtype() -> Result<(), ShellError> { test_polars_plugin_command(&ToDataType) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/schema.rs
crates/nu_plugin_polars/src/dataframe/command/core/schema.rs
use crate::{ PolarsPlugin, values::{CustomValueSupport, PolarsPluginObject, datatype_list}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Type, Value, record, }; #[derive(Clone)] pub struct SchemaCmd; impl PluginCommand for SchemaCmd { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars schema" } fn description(&self) -> &str { "Show schema for a dataframe." } fn signature(&self) -> Signature { Signature::build(self.name()) .switch("datatype-list", "creates a lazy dataframe", Some('l')) .input_output_type(Type::Any, Type::record()) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Dataframe schema", example: r#"[[a b]; [1 "foo"] [3 "bar"]] | polars into-df | polars schema"#, result: Some(Value::record( record! { "a" => Value::string("i64", Span::test_data()), "b" => Value::string("str", Span::test_data()), }, Span::test_data(), )), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { if call.has_flag("datatype-list")? { Ok(PipelineData::value(datatype_list(Span::unknown()), None)) } else { command(plugin, engine, call, input).map_err(LabeledError::from) } } } fn command( plugin: &PolarsPlugin, _engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { match PolarsPluginObject::try_from_pipeline(plugin, input, call.head)? { PolarsPluginObject::NuDataFrame(df) => { let schema = df.schema(); let value = schema.base_value(call.head)?; Ok(PipelineData::value(value, None)) } PolarsPluginObject::NuLazyFrame(mut lazy) => { let schema = lazy.schema()?; let value = schema.base_value(call.head)?; Ok(PipelineData::value(value, None)) } _ => Err(ShellError::GenericError { error: "Must be a dataframe or lazy dataframe".into(), msg: "".into(), span: Some(call.head), help: None, inner: vec![], }), } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&SchemaCmd) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/summary.rs
crates/nu_plugin_polars/src/dataframe/command/core/summary.rs
use crate::{PolarsPlugin, values::CustomValueSupport}; use crate::values::{Column, NuDataFrame, PolarsPluginType}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::{ chunked_array::ChunkedArray, prelude::{ AnyValue, Column as PolarsColumn, DataFrame, DataType, Float64Type, IntoSeries, NewChunkedArray, QuantileMethod, StringType, }, }; #[derive(Clone)] pub struct Summary; impl PluginCommand for Summary { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars summary" } fn description(&self) -> &str { "For a dataframe, produces descriptive statistics (summary statistics) for its numeric columns." } fn signature(&self) -> Signature { Signature::build(self.name()) .category(Category::Custom("dataframe".into())) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .named( "quantiles", SyntaxShape::List(Box::new(SyntaxShape::Float)), "provide optional quantiles", Some('q'), ) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "list dataframe descriptives", example: "[[a b]; [1 1] [1 1]] | polars into-df | polars summary", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "descriptor".to_string(), vec![ Value::test_string("count"), Value::test_string("sum"), Value::test_string("mean"), Value::test_string("median"), Value::test_string("std"), Value::test_string("min"), Value::test_string("25%"), Value::test_string("50%"), Value::test_string("75%"), Value::test_string("max"), ], ), Column::new( "a (i64)".to_string(), vec![ Value::test_float(2.0), Value::test_float(2.0), Value::test_float(1.0), Value::test_float(1.0), Value::test_float(0.0), Value::test_float(1.0), Value::test_float(1.0), Value::test_float(1.0), Value::test_float(1.0), Value::test_float(1.0), ], ), Column::new( "b (i64)".to_string(), vec![ Value::test_float(2.0), Value::test_float(2.0), Value::test_float(1.0), Value::test_float(1.0), Value::test_float(0.0), Value::test_float(1.0), Value::test_float(1.0), Value::test_float(1.0), Value::test_float(1.0), Value::test_float(1.0), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let quantiles: Option<Vec<Value>> = call.get_flag("quantiles")?; let quantiles = quantiles.map(|values| { values .iter() .map(|value| { let span = value.span(); match value { Value::Float { val, .. } => { if (&0.0..=&1.0).contains(&val) { Ok(*val) } else { Err(ShellError::GenericError { error: "Incorrect value for quantile".into(), msg: "value should be between 0 and 1".into(), span: Some(span), help: None, inner: vec![], }) } } Value::Error { error, .. } => Err(*error.clone()), _ => Err(ShellError::GenericError { error: "Incorrect value for quantile".into(), msg: "value should be a float".into(), span: Some(span), help: None, inner: vec![], }), } }) .collect::<Result<Vec<f64>, ShellError>>() }); let quantiles = match quantiles { Some(quantiles) => quantiles?, None => vec![0.25, 0.50, 0.75], }; let mut quantiles_labels = quantiles .iter() .map(|q| Some(format!("{}%", q * 100.0))) .collect::<Vec<Option<String>>>(); let mut labels = vec![ Some("count".to_string()), Some("sum".to_string()), Some("mean".to_string()), Some("median".to_string()), Some("std".to_string()), Some("min".to_string()), ]; labels.append(&mut quantiles_labels); labels.push(Some("max".to_string())); let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let names = ChunkedArray::<StringType>::from_slice_options("descriptor".into(), &labels).into_series(); let head = std::iter::once(names); let tail = df .as_ref() .iter() .filter(|col| !matches!(col.dtype(), &DataType::Object("object"))) .map(|col| { let count = col.len() as f64; let sum = col.sum::<f64>().ok(); let mean = col.mean(); let median = col.median(); let std = col.std(0); let min = col.min::<f64>().ok().flatten(); let mut quantiles = quantiles .clone() .into_iter() .map(|q| { col.quantile_reduce(q, QuantileMethod::default()) .ok() .map(|s| s.into_series("quantile".into())) .and_then(|ca| ca.cast(&DataType::Float64).ok()) .and_then(|ca| match ca.get(0) { Ok(AnyValue::Float64(v)) => Some(v), _ => None, }) }) .collect::<Vec<Option<f64>>>(); let max = col.max::<f64>().ok().flatten(); let mut descriptors = vec![Some(count), sum, mean, median, std, min]; descriptors.append(&mut quantiles); descriptors.push(max); let name = format!("{} ({})", col.name(), col.dtype()); ChunkedArray::<Float64Type>::from_slice_options(name.into(), &descriptors).into_series() }); let res = head .chain(tail) .map(PolarsColumn::from) .collect::<Vec<PolarsColumn>>(); let polars_df = DataFrame::new(res).map_err(|e| ShellError::GenericError { error: "Dataframe Error".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let df = NuDataFrame::new(df.from_lazy, polars_df); df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&Summary) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/mod.rs
crates/nu_plugin_polars/src/dataframe/command/core/mod.rs
mod cache; mod columns; mod open; mod profile; mod resource; mod save; mod schema; mod shape; mod summary; mod to_df; mod to_dtype; mod to_lazy; mod to_nu; mod to_repr; mod to_schema; pub use self::open::OpenDataFrame; use crate::PolarsPlugin; use nu_plugin::PluginCommand; pub use schema::SchemaCmd; pub use shape::ShapeDF; pub use summary::Summary; pub use to_df::ToDataFrame; pub use to_lazy::ToLazyFrame; pub use to_nu::ToNu; pub use to_repr::ToRepr; pub(crate) fn core_commands() -> Vec<Box<dyn PluginCommand<Plugin = PolarsPlugin>>> { vec![ Box::new(columns::ColumnsDF), Box::new(cache::LazyCache), Box::new(OpenDataFrame), Box::new(profile::ProfileDF), Box::new(Summary), Box::new(ShapeDF), Box::new(SchemaCmd), Box::new(ToNu), Box::new(ToDataFrame), Box::new(save::SaveDF), Box::new(ToLazyFrame), Box::new(ToRepr), Box::new(to_dtype::ToDataType), Box::new(to_schema::ToSchema), ] }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/to_nu.rs
crates/nu_plugin_polars/src/dataframe/command/core/to_nu.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value, record, }; use crate::{ PolarsPlugin, values::{CustomValueSupport, PolarsPluginObject, PolarsPluginType, cant_convert_err}, }; use crate::values::NuDataFrame; #[derive(Clone)] pub struct ToNu; impl PluginCommand for ToNu { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars into-nu" } fn description(&self) -> &str { "Converts a dataframe or an expression into nushell value for access and exploration." } fn signature(&self) -> Signature { Signature::build(self.name()) .named( "rows", SyntaxShape::Number, "number of rows to be shown", Some('n'), ) .switch("tail", "shows tail rows", Some('t')) .switch("index", "add an index column", Some('i')) .input_output_types( PolarsPluginType::types() .iter() .map(|t| match t { PolarsPluginType::NuDataFrame | PolarsPluginType::NuLazyFrame => { (Type::from(*t), Type::table()) } _ => (Type::from(*t), Type::Any), }) .collect(), ) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { let rec_1 = Value::test_record(record! { "index" => Value::test_int(0), "a" => Value::test_int(1), "b" => Value::test_int(2), }); let rec_2 = Value::test_record(record! { "index" => Value::test_int(1), "a" => Value::test_int(3), "b" => Value::test_int(4), }); let rec_3 = Value::test_record(record! { "index" => Value::test_int(2), "a" => Value::test_int(3), "b" => Value::test_int(4), }); vec![ Example { description: "Shows head rows from dataframe", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars into-nu --index", result: Some(Value::list(vec![rec_1, rec_2], Span::test_data())), }, Example { description: "Shows tail rows from dataframe", example: "[[a b]; [1 2] [5 6] [3 4]] | polars into-df | polars into-nu --tail --rows 1 --index", result: Some(Value::list(vec![rec_3], Span::test_data())), }, Example { description: "Convert a col expression into a nushell value", example: "polars col a | polars into-nu --index", result: Some(Value::test_record(record! { "expr" => Value::test_string("column"), "value" => Value::test_string("a"), })), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { command(plugin, engine, call, input).map_err(LabeledError::from) } } fn command( plugin: &PolarsPlugin, _engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => dataframe_command(call, df), PolarsPluginObject::NuLazyFrame(lazy) => dataframe_command(call, lazy.collect(call.head)?), PolarsPluginObject::NuExpression(expr) => { let value = expr.to_value(call.head)?; Ok(PipelineData::value(value, None)) } PolarsPluginObject::NuDataType(dt) => { let value = dt.base_value(call.head)?; Ok(PipelineData::value(value, None)) } PolarsPluginObject::NuSchema(schema) => { let value = schema.base_value(call.head)?; Ok(PipelineData::value(value, None)) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, PolarsPluginType::NuDataType, PolarsPluginType::NuSchema, ], )), } } fn dataframe_command(call: &EvaluatedCall, df: NuDataFrame) -> Result<PipelineData, ShellError> { let rows: Option<usize> = call.get_flag("rows")?; let tail: bool = call.has_flag("tail")?; let index: bool = call.has_flag("index")?; let values = if tail { df.tail(rows, index, call.head)? } else { // if rows is specified, return those rows, otherwise return everything if rows.is_some() { df.head(rows, index, call.head)? } else { df.head(Some(df.height()), index, call.head)? } }; let value = Value::list(values, call.head); Ok(PipelineData::value(value, None)) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ToNu) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/to_repr.rs
crates/nu_plugin_polars/src/dataframe/command/core/to_repr.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Type, Value, }; use crate::{ PolarsPlugin, values::{CustomValueSupport, NuLazyFrame, PolarsPluginType, cant_convert_err}, }; use crate::values::NuDataFrame; #[derive(Clone)] pub struct ToRepr; impl PluginCommand for ToRepr { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars into-repr" } fn description(&self) -> &str { "Display a dataframe in its repr format." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ (PolarsPluginType::NuDataFrame.into(), Type::String), (PolarsPluginType::NuLazyFrame.into(), Type::String), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Shows dataframe in repr format", example: "[[a b]; [2025-01-01 2] [2025-01-02 4]] | polars into-df | polars into-repr", result: Some(Value::string( r#" shape: (2, 2) ┌─────────────────────────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ datetime[ns, UTC] ┆ i64 │ ╞═════════════════════════╪═════╡ │ 2025-01-01 00:00:00 UTC ┆ 2 │ │ 2025-01-02 00:00:00 UTC ┆ 4 │ └─────────────────────────┴─────┘"# .trim(), Span::test_data(), )), }, Example { description: "Shows lazy dataframe in repr format", example: "[[a b]; [2025-01-01 2] [2025-01-02 4]] | polars into-lazy | polars into-repr", result: Some(Value::string( r#" shape: (2, 2) ┌─────────────────────────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ datetime[ns, UTC] ┆ i64 │ ╞═════════════════════════╪═════╡ │ 2025-01-01 00:00:00 UTC ┆ 2 │ │ 2025-01-02 00:00:00 UTC ┆ 4 │ └─────────────────────────┴─────┘"# .trim(), Span::test_data(), )), }, ] } fn run( &self, plugin: &Self::Plugin, _engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let value = input.into_value(call.head)?; if NuDataFrame::can_downcast(&value) || NuLazyFrame::can_downcast(&value) { dataframe_command(plugin, call, value) } else { Err(cant_convert_err( &value, &[PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame], )) } .map_err(|e| e.into()) } } fn dataframe_command( plugin: &PolarsPlugin, call: &EvaluatedCall, input: Value, ) -> Result<PipelineData, ShellError> { let df = NuDataFrame::try_from_value_coerce(plugin, &input, call.head)?; let value = Value::string(format!("{df}"), call.head); Ok(PipelineData::value(value, None)) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ToRepr) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/cache.rs
crates/nu_plugin_polars/src/dataframe/command/core/cache.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, Signature, Span}; use polars::df; use crate::{ PolarsPlugin, values::{CustomValueSupport, NuDataFrame, NuLazyFrame, PolarsPluginType}, }; pub struct LazyCache; impl PluginCommand for LazyCache { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars cache" } fn description(&self) -> &str { "Caches operations in a new LazyFrame." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Caches the result into a new LazyFrame", example: "[[a b]; [6 2] [4 2] [2 2]] | polars into-df | polars reverse | polars cache | polars sort-by a", result: Some( NuDataFrame::from( df!( "a" => [2i64, 4, 6], "b" => [2i64, 2, 2], ) .expect("should not fail"), ) .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let lazy = NuLazyFrame::try_from_pipeline_coerce(plugin, input, call.head) .map_err(LabeledError::from)?; let lazy = NuLazyFrame::new(lazy.from_eager, lazy.to_polars().cache()); lazy.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; use nu_protocol::ShellError; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&LazyCache) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/to_df.rs
crates/nu_plugin_polars/src/dataframe/command/core/to_df.rs
use crate::{ PolarsPlugin, dataframe::values::NuSchema, values::{Column, CustomValueSupport, PolarsPluginType}, }; use crate::values::NuDataFrame; use log::debug; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, Signature, Span, SyntaxShape, Type, Value, }; use polars::{ prelude::{AnyValue, DataType, Field, NamedFrom}, series::Series, }; #[derive(Clone)] pub struct ToDataFrame; impl PluginCommand for ToDataFrame { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars into-df" } fn description(&self) -> &str { "Converts a list, table or record into a dataframe." } fn signature(&self) -> Signature { Signature::build(self.name()) .named( "schema", SyntaxShape::Any, r#"Polars Schema in format [{name: str}]."#, Some('s'), ) .switch( "as-columns", r#"When input shape is record of lists, treat each list as column values."#, Some('c'), ) .input_output_type(Type::Any, PolarsPluginType::NuDataFrame.into()) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Takes a dictionary and creates a dataframe", example: "[[a b];[1 2] [3 4]] | polars into-df", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(3)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(4)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Takes a record of lists and creates a dataframe", example: "{a: [1 3], b: [2 4]} | polars into-df --as-columns", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(3)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(4)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Takes a list of tables and creates a dataframe", example: "[[1 2 a] [3 4 b] [5 6 c]] | polars into-df", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "0".to_string(), vec![Value::test_int(1), Value::test_int(3), Value::test_int(5)], ), Column::new( "1".to_string(), vec![Value::test_int(2), Value::test_int(4), Value::test_int(6)], ), Column::new( "2".to_string(), vec![ Value::test_string("a"), Value::test_string("b"), Value::test_string("c"), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Takes a list and creates a dataframe", example: "[a b c] | polars into-df", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_string("a"), Value::test_string("b"), Value::test_string("c"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Takes a list of booleans and creates a dataframe", example: "[true true false] | polars into-df", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_bool(true), Value::test_bool(true), Value::test_bool(false), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Convert to a dataframe and provide a schema", example: "[[a b c e]; [1 {d: [1 2 3]} [10 11 12] 1.618]]| polars into-df -s {a: u8, b: {d: list<u64>}, c: list<u8>, e: 'decimal<4,3>'}", result: Some( NuDataFrame::try_from_series_vec( vec![ Series::new("a".into(), &[1u8]), { let dtype = DataType::Struct(vec![Field::new( "d".into(), DataType::List(Box::new(DataType::UInt64)), )]); let vals = vec![ AnyValue::StructOwned(Box::new(( vec![AnyValue::List(Series::new( "d".into(), &[1u64, 2, 3] ))], vec![Field::new("d".into(), DataType::String)] ))); 1 ]; Series::from_any_values_and_dtype("b".into(), &vals, &dtype, false) .expect("Struct series should not fail") }, { let dtype = DataType::List(Box::new(DataType::UInt8)); let vals = vec![AnyValue::List(Series::new("c".into(), &[10, 11, 12]))]; Series::from_any_values_and_dtype("c".into(), &vals, &dtype, false) .expect("List series should not fail") }, Series::new("e".into(), &[1.618]), ], Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Convert to a dataframe and provide a schema that adds a new column", example: r#"[[a b]; [1 "foo"] [2 "bar"]] | polars into-df -s {a: u8, b:str, c:i64} | polars fill-null 3"#, result: Some( NuDataFrame::try_from_series_vec( vec![ Series::new("a".into(), [1u8, 2]), Series::new("b".into(), ["foo", "bar"]), Series::new("c".into(), [3i64, 3]), ], Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "If a provided schema specifies a subset of columns, only those columns are selected", example: r#"[[a b]; [1 "foo"] [2 "bar"]] | polars into-df -s {a: str}"#, result: Some( NuDataFrame::try_from_series_vec( vec![Series::new("a".into(), ["1", "2"])], Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Use a predefined schama", example: r#"let schema = {a: str, b: str}; [[a b]; [1 "foo"] [2 "bar"]] | polars into-df -s $schema"#, result: Some( NuDataFrame::try_from_series_vec( vec![ Series::new("a".into(), ["1", "2"]), Series::new("b".into(), ["foo", "bar"]), ], Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let maybe_schema = call .get_flag("schema")? .map(|schema| NuSchema::try_from_value(plugin, &schema)) .transpose()?; debug!("schema: {maybe_schema:?}"); let maybe_as_columns = call.has_flag("as-columns")?; let df = if !maybe_as_columns { NuDataFrame::try_from_iter(plugin, input.into_iter(), maybe_schema.clone())? } else { match &input { PipelineData::Value(Value::Record { val, .. }, _) => { let items: Result<Vec<(String, Vec<Value>)>, &str> = val .iter() .map(|(k, v)| match v.to_owned().into_list() { Ok(v) => Ok((k.to_owned(), v)), _ => Err("error"), }) .collect(); match items { Ok(items) => { let columns = items .iter() .map(|(k, v)| Column::new(k.to_owned(), v.to_owned())) .collect::<Vec<Column>>(); NuDataFrame::try_from_columns(columns, maybe_schema)? } Err(e) => { debug!( "Failed to build with multiple columns, attempting as series. failure:{e}" ); NuDataFrame::try_from_iter( plugin, input.into_iter(), maybe_schema.clone(), )? } } } _ => { debug!("Other input: {input:?}"); NuDataFrame::try_from_iter(plugin, input.into_iter(), maybe_schema.clone())? } } }; df.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; use nu_protocol::ShellError; #[test] fn test_into_df() -> Result<(), ShellError> { test_polars_plugin_command(&ToDataFrame) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/to_lazy.rs
crates/nu_plugin_polars/src/dataframe/command/core/to_lazy.rs
use crate::{Cacheable, PolarsPlugin, dataframe::values::NuSchema, values::CustomValueSupport}; use crate::values::{NuDataFrame, NuLazyFrame, PolarsPluginType}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, Signature, Span, SyntaxShape, Type, Value, record, }; use polars::prelude::NamedFrom; use polars::series::Series; #[derive(Clone)] pub struct ToLazyFrame; impl PluginCommand for ToLazyFrame { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars into-lazy" } fn description(&self) -> &str { "Converts a dataframe into a lazy dataframe." } fn signature(&self) -> Signature { Signature::build(self.name()) .named( "schema", SyntaxShape::Any, r#"Polars Schema in format [{name: str}]."#, Some('s'), ) .input_output_type(Type::Any, PolarsPluginType::NuLazyFrame.into()) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Takes a table and creates a lazyframe", example: "[[a b];[1 2] [3 4]] | polars into-lazy", result: None, }, Example { description: "Takes a table, creates a lazyframe, assigns column 'b' type str, displays the schema", example: "[[a b];[1 2] [3 4]] | polars into-lazy --schema {b: str} | polars schema", result: Some(Value::test_record( record! {"b" => Value::test_string("str")}, )), }, Example { description: "Use a predefined schama", example: r#"let schema = {a: str, b: str}; [[a b]; [1 "foo"] [2 "bar"]] | polars into-lazy -s $schema"#, result: Some( NuDataFrame::try_from_series_vec( vec![ Series::new("a".into(), ["1", "2"]), Series::new("b".into(), ["foo", "bar"]), ], Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let maybe_schema = call .get_flag("schema")? .map(|schema| NuSchema::try_from_value(plugin, &schema)) .transpose()?; let df = NuDataFrame::try_from_iter(plugin, input.into_iter(), maybe_schema)?; let mut lazy = NuLazyFrame::from_dataframe(df); // We don't want this converted back to an eager dataframe at some point lazy.from_eager = false; Ok(PipelineData::value( lazy.cache(plugin, engine, call.head)?.into_value(call.head), None, )) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod tests { use crate::test::test_polars_plugin_command; use std::sync::Arc; use nu_plugin_test_support::PluginTest; use nu_protocol::{ShellError, Span}; use super::*; #[test] fn test_to_lazy() -> Result<(), ShellError> { let plugin: Arc<PolarsPlugin> = PolarsPlugin::new_test_mode()?.into(); let mut plugin_test = PluginTest::new("polars", Arc::clone(&plugin))?; let pipeline_data = plugin_test.eval("[[a b]; [6 2] [1 4] [4 1]] | polars into-lazy")?; let value = pipeline_data.into_value(Span::test_data())?; let df = NuLazyFrame::try_from_value(&plugin, &value)?; assert!(!df.from_eager); Ok(()) } #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ToLazyFrame) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/profile.rs
crates/nu_plugin_polars/src/dataframe/command/core/profile.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Value, record, }; use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuDataFrame, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; pub struct ProfileDF; impl PluginCommand for ProfileDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars profile" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn description(&self) -> &str { "Profile a lazy dataframe." } fn extra_description(&self) -> &str { r#"This will run the query and return a record containing the materialized DataFrame and a DataFrame that contains profiling information of each node that is executed. The units of the timings are microseconds."# } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Profile a lazy dataframe", example: r#"[[a b]; [1 2] [1 4] [2 6] [2 4]] | polars into-lazy | polars group-by a | polars agg [ (polars col b | polars min | polars as "b_min") (polars col b | polars max | polars as "b_max") (polars col b | polars sum | polars as "b_sum") ] | polars profile "#, result: None, }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_lazy(plugin, engine, call, df.lazy()), PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), _ => Err(cant_convert_err( &value, &[PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let (df, profiling_df) = lazy .to_polars() .profile() .map_err(|e| ShellError::GenericError { error: format!("Could not profile dataframe: {e}"), msg: "".into(), span: Some(call.head), help: None, inner: vec![], })?; let df = NuDataFrame::from(df).cache_and_to_value(plugin, engine, call.head)?; let profiling_df = NuDataFrame::from(profiling_df).cache_and_to_value(plugin, engine, call.head)?; let result = Value::record( record!( "dataframe" => df, "profiling" => profiling_df, ), call.head, ); Ok(PipelineData::value(result, None)) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/save/ndjson.rs
crates/nu_plugin_polars/src/dataframe/command/core/save/ndjson.rs
use std::{fs::File, io::BufWriter, path::PathBuf}; use log::debug; use nu_plugin::EvaluatedCall; use nu_protocol::ShellError; use polars::prelude::{JsonWriter, JsonWriterOptions, SerWriter, SinkOptions}; use crate::{ command::core::resource::Resource, values::{NuDataFrame, NuLazyFrame}, }; use super::polars_file_save_error; pub(crate) fn command_lazy( _call: &EvaluatedCall, lazy: &NuLazyFrame, resource: Resource, ) -> Result<(), ShellError> { let file_path = resource.as_string(); let file_span = resource.span; debug!("Writing ndjson file {file_path}"); lazy.to_polars() .sink_json( resource.clone().into(), JsonWriterOptions::default(), resource.cloud_options, SinkOptions::default(), ) .and_then(|l| l.collect()) .map_err(|e| polars_file_save_error(e, file_span)) .map(|_| { debug!("Wrote ndjson file {file_path}"); }) } pub(crate) fn command_eager(df: &NuDataFrame, resource: Resource) -> Result<(), ShellError> { let file_span = resource.span; let file_path: PathBuf = resource.try_into()?; let file = File::create(file_path).map_err(|e| ShellError::GenericError { error: format!("Error with file name: {e}"), msg: "".into(), span: Some(file_span), help: None, inner: vec![], })?; let buf_writer = BufWriter::new(file); JsonWriter::new(buf_writer) .finish(&mut df.to_polars()) .map_err(|e| ShellError::GenericError { error: "Error saving file".into(), msg: e.to_string(), span: Some(file_span), help: None, inner: vec![], })?; Ok(()) } #[cfg(test)] pub mod test { use crate::command::core::save::test::{test_eager_save, test_lazy_save}; #[test] pub fn test_ndjson_eager_save() -> Result<(), Box<dyn std::error::Error>> { test_eager_save("ndjson") } #[test] pub fn test_ndjson_lazy_save() -> Result<(), Box<dyn std::error::Error>> { test_lazy_save("ndjson") } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/save/arrow.rs
crates/nu_plugin_polars/src/dataframe/command/core/save/arrow.rs
use std::{fs::File, path::PathBuf}; use log::debug; use nu_plugin::EvaluatedCall; use nu_protocol::ShellError; use polars::prelude::{IpcWriter, IpcWriterOptions, SerWriter, SinkOptions}; use crate::{ command::core::resource::Resource, values::{NuDataFrame, NuLazyFrame}, }; use super::polars_file_save_error; pub(crate) fn command_lazy( _call: &EvaluatedCall, lazy: &NuLazyFrame, resource: Resource, ) -> Result<(), ShellError> { let file_path = resource.as_string(); let file_span = resource.span; debug!("Writing ipc file {file_path}"); lazy.to_polars() .sink_ipc( resource.clone().into(), IpcWriterOptions::default(), resource.cloud_options, SinkOptions::default(), ) .and_then(|l| l.collect()) .map(|_| { debug!("Wrote ipc file {file_path}"); }) .map_err(|e| polars_file_save_error(e, file_span)) } pub(crate) fn command_eager(df: &NuDataFrame, resource: Resource) -> Result<(), ShellError> { let file_span = resource.span; let file_path: PathBuf = resource.try_into()?; let mut file = File::create(file_path).map_err(|e| ShellError::GenericError { error: format!("Error with file name: {e}"), msg: "".into(), span: Some(file_span), help: None, inner: vec![], })?; IpcWriter::new(&mut file) .finish(&mut df.to_polars()) .map_err(|e| ShellError::GenericError { error: "Error saving file".into(), msg: e.to_string(), span: Some(file_span), help: None, inner: vec![], })?; Ok(()) } #[cfg(test)] pub mod test { use crate::command::core::save::test::{test_eager_save, test_lazy_save}; #[test] pub fn test_arrow_eager_save() -> Result<(), Box<dyn std::error::Error>> { test_eager_save("arrow") } #[test] pub fn test_arrow_lazy_save() -> Result<(), Box<dyn std::error::Error>> { test_lazy_save("arrow") } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/save/mod.rs
crates/nu_plugin_polars/src/dataframe/command/core/save/mod.rs
mod arrow; mod avro; mod csv; mod ndjson; mod parquet; use std::path::PathBuf; use crate::{ PolarsPlugin, command::core::resource::Resource, values::{PolarsFileType, PolarsPluginObject, PolarsPluginType, cant_convert_err}, }; use log::debug; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, DataSource, Example, LabeledError, PipelineData, PipelineMetadata, ShellError, Signature, Span, Spanned, SyntaxShape, Type, shell_error::{self, io::IoError}, }; use polars::error::PolarsError; #[derive(Clone)] pub struct SaveDF; impl PluginCommand for SaveDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars save" } fn description(&self) -> &str { "Saves a dataframe to disk. For lazy dataframes a sink operation will be used if the file type supports it (parquet, ipc/arrow, csv, and ndjson)." } fn signature(&self) -> Signature { Signature::build(self.name()) .required("path", SyntaxShape::String, "Path or cloud url to write to") .named( "type", SyntaxShape::String, "File type: csv, json, parquet, arrow/ipc. If omitted, derive from file extension", Some('t'), ) .named( "avro-compression", SyntaxShape::String, "Compression for avro supports deflate or snappy", None, ) .named( "csv-delimiter", SyntaxShape::String, "file delimiter character", None, ) .switch( "csv-no-header", "Indicates to exclude a header row for CSV files.", None, ) .input_output_type(Type::Any, Type::String) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Performs a streaming collect and save the output to the specified file", example: "[[a b];[1 2] [3 4]] | polars into-lazy | polars save test.parquet", result: None, }, Example { description: "Saves dataframe to parquet file", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars save test.parquet", result: None, }, Example { description: "Saves dataframe to arrow file", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars save test.arrow", result: None, }, Example { description: "Saves dataframe to NDJSON file", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars save test.ndjson", result: None, }, Example { description: "Saves dataframe to avro file", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars save test.avro", result: None, }, Example { description: "Saves dataframe to CSV file", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars save test.csv", result: None, }, Example { description: "Saves dataframe to CSV file using other delimiter", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars save test.csv --csv-delimiter '|'", result: None, }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let spanned_file: Spanned<String> = call.req(0)?; debug!("file: {}", spanned_file.item); let metadata = input.metadata(); let value = input.into_value(call.head)?; check_writing_into_source_file( metadata.as_ref(), &spanned_file.as_ref().map(PathBuf::from), )?; match PolarsPluginObject::try_from_value(plugin, &value)? { po @ PolarsPluginObject::NuDataFrame(_) | po @ PolarsPluginObject::NuLazyFrame(_) => { command(plugin, engine, call, po, spanned_file) } _ => Err(cant_convert_err( &value, &[PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame], )), } .map_err(LabeledError::from) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, polars_object: PolarsPluginObject, spanned_file: Spanned<String>, ) -> Result<PipelineData, ShellError> { let resource = Resource::new(plugin, engine, &spanned_file)?; let type_option: Option<(String, Span)> = call .get_flag("type")? .map(|t: Spanned<String>| (t.item, t.span)) .or_else(|| { resource .path .as_ref() .extension() .map(|ext| (ext.to_owned(), resource.span)) }); debug!("resource: {resource:?}"); match type_option { Some((ext, blamed)) => match PolarsFileType::from(ext.as_str()) { PolarsFileType::Parquet => match polars_object { PolarsPluginObject::NuLazyFrame(ref lazy) => { parquet::command_lazy(call, lazy, resource) } PolarsPluginObject::NuDataFrame(ref df) if resource.cloud_options.is_some() => { parquet::command_lazy(call, &df.lazy(), resource) } PolarsPluginObject::NuDataFrame(ref df) => parquet::command_eager(df, resource), _ => Err(unknown_file_save_error(resource.span)), }, PolarsFileType::Arrow => match polars_object { PolarsPluginObject::NuLazyFrame(ref lazy) => { arrow::command_lazy(call, lazy, resource) } PolarsPluginObject::NuDataFrame(ref df) if resource.cloud_options.is_some() => { arrow::command_lazy(call, &df.lazy(), resource) } PolarsPluginObject::NuDataFrame(ref df) => arrow::command_eager(df, resource), _ => Err(unknown_file_save_error(resource.span)), }, PolarsFileType::NdJson => match polars_object { PolarsPluginObject::NuLazyFrame(ref lazy) => { ndjson::command_lazy(call, lazy, resource) } PolarsPluginObject::NuDataFrame(ref df) if resource.cloud_options.is_some() => { ndjson::command_lazy(call, &df.lazy(), resource) } PolarsPluginObject::NuDataFrame(ref df) => ndjson::command_eager(df, resource), _ => Err(unknown_file_save_error(resource.span)), }, PolarsFileType::Avro => match polars_object { _ if resource.cloud_options.is_some() => Err(ShellError::GenericError { error: "Cloud URLS are not supported with Avro".into(), msg: "".into(), span: call.get_flag_span("eager"), help: Some("Remove flag".into()), inner: vec![], }), PolarsPluginObject::NuLazyFrame(lazy) => { let df = lazy.collect(call.head)?; avro::command_eager(call, &df, resource) } PolarsPluginObject::NuDataFrame(ref df) => avro::command_eager(call, df, resource), _ => Err(unknown_file_save_error(resource.span)), }, PolarsFileType::Csv => match polars_object { PolarsPluginObject::NuLazyFrame(ref lazy) => { csv::command_lazy(call, lazy, resource) } PolarsPluginObject::NuDataFrame(ref df) if resource.cloud_options.is_some() => { csv::command_lazy(call, &df.lazy(), resource) } PolarsPluginObject::NuDataFrame(ref df) => csv::command_eager(call, df, resource), _ => Err(unknown_file_save_error(resource.span)), }, _ => Err(PolarsFileType::build_unsupported_error( &ext, &[ PolarsFileType::Parquet, PolarsFileType::Csv, PolarsFileType::Arrow, PolarsFileType::NdJson, PolarsFileType::Avro, ], blamed, )), }, None => Err(ShellError::Io(IoError::new_with_additional_context( shell_error::io::ErrorKind::FileNotFound, resource.span, Some(PathBuf::from(resource.as_string())), "File without extension", ))), }?; Ok(PipelineData::empty()) } fn check_writing_into_source_file( metadata: Option<&PipelineMetadata>, dest: &Spanned<PathBuf>, ) -> Result<(), ShellError> { let Some(DataSource::FilePath(source)) = metadata.map(|meta| &meta.data_source) else { return Ok(()); }; if &dest.item == source { return Err(write_into_source_error(dest.span)); } Ok(()) } fn write_into_source_error(span: Span) -> ShellError { polars_file_save_error( PolarsError::InvalidOperation("attempted to save into source".into()), span, ) } pub(crate) fn polars_file_save_error(e: PolarsError, span: Span) -> ShellError { ShellError::GenericError { error: format!("Error saving file: {e}"), msg: "".into(), span: Some(span), help: None, inner: vec![], } } pub fn unknown_file_save_error(span: Span) -> ShellError { ShellError::GenericError { error: "Could not save file for unknown reason".into(), msg: "".into(), span: Some(span), help: None, inner: vec![], } } #[cfg(test)] pub(crate) mod test { use nu_plugin_test_support::PluginTest; use nu_protocol::{Span, Value}; use tempfile::TempDir; use uuid::Uuid; use crate::PolarsPlugin; fn tmp_dir_sandbox() -> Result<(TempDir, PluginTest), Box<dyn std::error::Error>> { let tmp_dir = tempfile::tempdir()?; let mut plugin_test = PluginTest::new("polars", PolarsPlugin::new()?.into())?; plugin_test.engine_state_mut().add_env_var( "PWD".to_string(), Value::string( tmp_dir .path() .to_str() .expect("should be able to get path") .to_owned(), Span::test_data(), ), ); Ok((tmp_dir, plugin_test)) } fn test_save(cmd: &'static str, extension: &str) -> Result<(), Box<dyn std::error::Error>> { let (tmp_dir, mut plugin_test) = tmp_dir_sandbox()?; let mut tmp_file = tmp_dir.path().to_owned(); tmp_file.push(format!("{}.{}", Uuid::new_v4(), extension)); let tmp_file_str = tmp_file.to_str().expect("should be able to get file path"); let cmd = format!("{cmd} {tmp_file_str}"); let _pipeline_data = plugin_test.eval(&cmd)?; assert!(tmp_file.exists()); Ok(()) } pub fn test_lazy_save(extension: &str) -> Result<(), Box<dyn std::error::Error>> { test_save( "[[a b]; [1 2] [3 4]] | polars into-lazy | polars save", extension, ) } pub fn test_eager_save(extension: &str) -> Result<(), Box<dyn std::error::Error>> { test_save( "[[a b]; [1 2] [3 4]] | polars into-df | polars save", extension, ) } #[test] fn test_write_to_source_guard() -> Result<(), Box<dyn std::error::Error>> { let (tmp_dir, mut plugin_test) = tmp_dir_sandbox()?; let mut tmp_file = tmp_dir.path().to_owned(); dbg!(&tmp_dir); tmp_file.push(format!("{}.{}", Uuid::new_v4(), "parquet")); let tmp_file_str = tmp_file.to_str().expect("Should be able to get file path"); let _setup = plugin_test.eval(&format!( "[1 2 3] | polars into-df | polars save {tmp_file_str}", ))?; let output = plugin_test.eval(&format!( "polars open {tmp_file_str} | polars save {tmp_file_str}" )); assert!(output.is_err_and(|e| { e.to_string() .contains("Error saving file: attempted to save into source") })); Ok(()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/save/csv.rs
crates/nu_plugin_polars/src/dataframe/command/core/save/csv.rs
use std::{fs::File, path::PathBuf}; use log::debug; use nu_plugin::EvaluatedCall; use nu_protocol::{ShellError, Spanned}; use polars::prelude::{CsvWriter, SerWriter, SinkOptions}; use polars_io::csv::write::{CsvWriterOptions, SerializeOptions}; use crate::{ command::core::resource::Resource, values::{NuDataFrame, NuLazyFrame}, }; use super::polars_file_save_error; pub(crate) fn command_lazy( call: &EvaluatedCall, lazy: &NuLazyFrame, resource: Resource, ) -> Result<(), ShellError> { let file_span = resource.span; let file_path = resource.as_string(); debug!("Writing csv file {file_path}"); let delimiter: Option<Spanned<String>> = call.get_flag("csv-delimiter")?; let separator = delimiter .and_then(|d| d.item.chars().next().map(|c| c as u8)) .unwrap_or(b','); let no_header: bool = call.has_flag("csv-no-header")?; let options = CsvWriterOptions { include_header: !no_header, serialize_options: SerializeOptions { separator, ..SerializeOptions::default() }, ..CsvWriterOptions::default() }; lazy.to_polars() .sink_csv( resource.clone().into(), options, resource.cloud_options, SinkOptions::default(), ) .and_then(|l| l.collect()) .map_err(|e| polars_file_save_error(e, file_span)) .map(|_| { debug!("Wrote parquet file {file_path}"); }) } pub(crate) fn command_eager( call: &EvaluatedCall, df: &NuDataFrame, resource: Resource, ) -> Result<(), ShellError> { let file_span = resource.span; let file_path: PathBuf = resource.try_into()?; let delimiter: Option<Spanned<String>> = call.get_flag("csv-delimiter")?; let no_header: bool = call.has_flag("csv-no-header")?; let mut file = File::create(file_path).map_err(|e| ShellError::GenericError { error: format!("Error with file name: {e}"), msg: "".into(), span: Some(file_span), help: None, inner: vec![], })?; let writer = CsvWriter::new(&mut file); let writer = if no_header { writer.include_header(false) } else { writer.include_header(true) }; let mut writer = match delimiter { None => writer, Some(d) => { if d.item.len() != 1 { return Err(ShellError::GenericError { error: "Incorrect delimiter".into(), msg: "Delimiter has to be one char".into(), span: Some(d.span), help: None, inner: vec![], }); } else { let delimiter = match d.item.chars().next() { Some(d) => d as u8, None => unreachable!(), }; writer.with_separator(delimiter) } } }; writer .finish(&mut df.to_polars()) .map_err(|e| ShellError::GenericError { error: format!("Error writing to file: {e}"), msg: e.to_string(), span: Some(file_span), help: None, inner: vec![], })?; Ok(()) } #[cfg(test)] pub mod test { use crate::command::core::save::test::{test_eager_save, test_lazy_save}; #[test] pub fn test_csv_eager_save() -> Result<(), Box<dyn std::error::Error>> { test_eager_save("csv") } #[test] pub fn test_csv_lazy_save() -> Result<(), Box<dyn std::error::Error>> { test_lazy_save("csv") } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/save/parquet.rs
crates/nu_plugin_polars/src/dataframe/command/core/save/parquet.rs
use std::{fs::File, path::PathBuf}; use log::debug; use nu_plugin::EvaluatedCall; use nu_protocol::ShellError; use polars::prelude::{ParquetWriteOptions, ParquetWriter, SinkOptions}; use crate::{ command::core::resource::Resource, values::{NuDataFrame, NuLazyFrame}, }; use super::polars_file_save_error; pub(crate) fn command_lazy( _call: &EvaluatedCall, lazy: &NuLazyFrame, resource: Resource, ) -> Result<(), ShellError> { let file_path = resource.as_string(); let file_span = resource.span; debug!("Writing parquet file {file_path}"); lazy.to_polars() .sink_parquet( resource.clone().into(), ParquetWriteOptions::default(), resource.cloud_options, SinkOptions::default(), ) .and_then(|l| l.collect()) .map_err(|e| polars_file_save_error(e, file_span)) .map(|_| { debug!("Wrote parquet file {file_path}"); }) } pub(crate) fn command_eager(df: &NuDataFrame, resource: Resource) -> Result<(), ShellError> { let file_span = resource.span; let file_path: PathBuf = resource.try_into()?; let file = File::create(file_path).map_err(|e| ShellError::GenericError { error: "Error with file name".into(), msg: e.to_string(), span: Some(file_span), help: None, inner: vec![], })?; let mut polars_df = df.to_polars(); ParquetWriter::new(file) .finish(&mut polars_df) .map_err(|e| ShellError::GenericError { error: "Error saving file".into(), msg: e.to_string(), span: Some(file_span), help: None, inner: vec![], })?; Ok(()) } #[cfg(test)] pub(crate) mod test { use crate::command::core::save::test::{test_eager_save, test_lazy_save}; #[test] pub fn test_parquet_eager_save() -> Result<(), Box<dyn std::error::Error>> { test_eager_save("parquet") } #[test] pub fn test_parquet_lazy_save() -> Result<(), Box<dyn std::error::Error>> { test_lazy_save("parquet") } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/core/save/avro.rs
crates/nu_plugin_polars/src/dataframe/command/core/save/avro.rs
use std::fs::File; use std::path::PathBuf; use nu_plugin::EvaluatedCall; use nu_protocol::ShellError; use polars_io::SerWriter; use polars_io::avro::{AvroCompression, AvroWriter}; use crate::command::core::resource::Resource; use crate::values::NuDataFrame; fn get_compression(call: &EvaluatedCall) -> Result<Option<AvroCompression>, ShellError> { if let Some((compression, span)) = call .get_flag_value("avro-compression") .map(|e| e.as_str().map(|s| (s.to_owned(), e.span()))) .transpose()? { match compression.as_ref() { "snappy" => Ok(Some(AvroCompression::Snappy)), "deflate" => Ok(Some(AvroCompression::Deflate)), _ => Err(ShellError::IncorrectValue { msg: "compression must be one of deflate or snappy".to_string(), val_span: span, call_span: span, }), } } else { Ok(None) } } pub(crate) fn command_eager( call: &EvaluatedCall, df: &NuDataFrame, resource: Resource, ) -> Result<(), ShellError> { let file_span = resource.span; let compression = get_compression(call)?; let path: PathBuf = resource.try_into()?; let file = File::create(&path).map_err(|e| ShellError::GenericError { error: format!("Error with file name: {e}"), msg: "".into(), span: Some(file_span), help: None, inner: vec![], })?; AvroWriter::new(file) .with_compression(compression) .finish(&mut df.to_polars()) .map_err(|e| ShellError::GenericError { error: "Error saving file".into(), msg: e.to_string(), span: Some(file_span), help: None, inner: vec![], })?; Ok(()) } #[cfg(test)] pub mod test { use crate::command::core::save::test::{test_eager_save, test_lazy_save}; #[test] pub fn test_avro_eager_save() -> Result<(), Box<dyn std::error::Error>> { test_eager_save("avro") } #[test] pub fn test_avro_lazy_save() -> Result<(), Box<dyn std::error::Error>> { test_lazy_save("avro") } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/slice.rs
crates/nu_plugin_polars/src/dataframe/command/data/slice.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use crate::{PolarsPlugin, dataframe::values::Column, values::CustomValueSupport}; use crate::values::{NuDataFrame, NuLazyFrame, PolarsPluginObject, PolarsPluginType}; #[derive(Clone)] pub struct SliceDF; impl PluginCommand for SliceDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars slice" } fn description(&self) -> &str { "Creates new dataframe from a slice of rows." } fn signature(&self) -> Signature { Signature::build(self.name()) .required("offset", SyntaxShape::Int, "start of slice") .required("size", SyntaxShape::Int, "size of slice") .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Create new dataframe from a slice of the rows", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars slice 0 1", result: Some( NuDataFrame::try_from_columns( vec![ Column::new("a".to_string(), vec![Value::test_int(1)]), Column::new("b".to_string(), vec![Value::test_int(2)]), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Create a new lazy dataframe from a slice of a lazy dataframe's rows", example: "[[a b]; [1 2] [3 4]] | polars into-lazy | polars slice 0 1 | describe", result: Some(Value::test_string("polars_lazyframe")), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuLazyFrame(lazy) => { command_lazy(plugin, engine, call, lazy).map_err(|e| e.into()) } _ => { let df = NuDataFrame::try_from_value_coerce(plugin, &value, call.head)?; command_eager(plugin, engine, call, df).map_err(LabeledError::from) } } .map(|pd| pd.set_metadata(metadata)) } } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let offset: i64 = call.req(0)?; let size: usize = call.req(1)?; let res = df.as_ref().slice(offset, size); let res = NuDataFrame::new(false, res); res.to_pipeline_data(plugin, engine, call.head) } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let offset: i64 = call.req(0)?; let size: u64 = call.req(1)?; let res: NuLazyFrame = lazy.to_polars().slice(offset, size).into(); //.limit(rows).into(); res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&SliceDF) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/first.rs
crates/nu_plugin_polars/src/dataframe/command/data/first.rs
use crate::{ PolarsPlugin, values::{ Column, CustomValueSupport, NuLazyFrame, NuLazyGroupBy, PolarsPluginObject, PolarsPluginType, }, }; use crate::values::{NuDataFrame, NuExpression}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::df; #[derive(Clone)] pub struct FirstDF; impl PluginCommand for FirstDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars first" } fn description(&self) -> &str { "Show only the first number of rows or create a first expression" } fn signature(&self) -> Signature { Signature::build(self.name()) .optional( "rows", SyntaxShape::Int, "starting from the front, the number of rows to return", ) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Return the first row of a dataframe", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars first", result: Some( NuDataFrame::try_from_columns( vec![ Column::new("a".to_string(), vec![Value::test_int(1)]), Column::new("b".to_string(), vec![Value::test_int(2)]), ], None, ) .expect("should not fail") .into_value(Span::test_data()), ), }, Example { description: "Return the first two rows of a dataframe", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars first 2", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(3)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(4)], ), ], None, ) .expect("should not fail") .into_value(Span::test_data()), ), }, Example { description: "Creates a first expression from a column", example: "polars col a | polars first", result: None, }, Example { description: "Aggregate the first values in the group.", example: "[[a b c d]; [1 0.5 true Apple] [2 0.5 true Orange] [2 4 true Apple] [3 10 false Apple] [4 13 false Banana] [5 14 true Banana]] | polars into-df -s {a: u8, b: f32, c: bool, d: str} | polars group-by d | polars first | polars sort-by [a] | polars collect", result: Some( NuDataFrame::new( false, df!( "d" => &["Apple", "Orange", "Banana"], "a" => &[1, 2, 4], "b" => &[0.5, 0.5, 13.0], "c" => &[true, true, false], ) .expect("dataframe creation should succeed"), ) .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => { command_eager(plugin, engine, call, df).map_err(|e| e.into()) } PolarsPluginObject::NuLazyFrame(lazy) => { command_lazy(plugin, engine, call, lazy).map_err(|e| e.into()) } PolarsPluginObject::NuLazyGroupBy(groupby) => { command_groupby(plugin, engine, call, groupby).map_err(|e| e.into()) } _ => { let expr = NuExpression::try_from_value(plugin, &value)?; let expr: NuExpression = expr.into_polars().first().into(); expr.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) } } .map(|pd| pd.set_metadata(metadata)) } } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let rows: Option<usize> = call.opt(0)?; let rows = rows.unwrap_or(1); let res = df.as_ref().head(Some(rows)); let res = NuDataFrame::new(false, res); res.to_pipeline_data(plugin, engine, call.head) } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let rows: Option<u64> = call.opt(0)?; let rows = rows.unwrap_or(1); let res: NuLazyFrame = lazy.to_polars().limit(rows).into(); res.to_pipeline_data(plugin, engine, call.head) } fn command_groupby( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, groupby: NuLazyGroupBy, ) -> Result<PipelineData, ShellError> { let rows: Option<usize> = call.opt(0)?; let rows = rows.unwrap_or(1); let res = groupby.to_polars().head(Some(rows)); let res: NuLazyFrame = res.into(); res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { // // Extensions are required for the group-by functionality to work // unsafe { // std::env::set_var("POLARS_ALLOW_EXTENSION", "true"); // } test_polars_plugin_command(&FirstDF) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/drop_nulls.rs
crates/nu_plugin_polars/src/dataframe/command/data/drop_nulls.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use crate::PolarsPlugin; use crate::values::{CustomValueSupport, PolarsPluginType}; use crate::values::utils::convert_columns_string; use crate::values::{Column, NuDataFrame}; #[derive(Clone)] pub struct DropNulls; impl PluginCommand for DropNulls { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars drop-nulls" } fn description(&self) -> &str { "Drops null values in dataframe." } fn signature(&self) -> Signature { Signature::build(self.name()) .optional( "subset", SyntaxShape::Table(vec![]), "subset of columns to drop nulls", ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "drop null values in dataframe", example: r#"let df = ([[a b]; [1 2] [3 0] [1 2]] | polars into-df); let res = ($df.b / $df.b); let a = ($df | polars with-column $res --name res); $a | polars drop-nulls"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(1)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(2)], ), Column::new( "res".to_string(), vec![Value::test_int(1), Value::test_int(1)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "drop null values in dataframe", example: r#"let s = ([1 2 0 0 3 4] | polars into-df); ($s / $s) | polars drop-nulls"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "div_0_0".to_string(), vec![ Value::test_int(1), Value::test_int(1), Value::test_int(1), Value::test_int(1), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let columns: Option<Vec<Value>> = call.opt(0)?; let (subset, col_span) = match columns { Some(cols) => { let (agg_string, col_span) = convert_columns_string(cols, call.head)?; (Some(agg_string), col_span) } None => (None, call.head), }; let subset_slice = subset.as_ref().map(|cols| &cols[..]); let polars_df = df .as_ref() .drop_nulls(subset_slice) .map_err(|e| ShellError::GenericError { error: "Error dropping nulls".into(), msg: e.to_string(), span: Some(col_span), help: None, inner: vec![], })?; let df = NuDataFrame::new(df.from_lazy, polars_df); df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&DropNulls) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/reverse.rs
crates/nu_plugin_polars/src/dataframe/command/data/reverse.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, Signature, Span, Value}; use crate::{ PolarsPlugin, values::{Column, CustomValueSupport, NuDataFrame, NuLazyFrame, PolarsPluginType}, }; pub struct LazyReverse; impl PluginCommand for LazyReverse { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars reverse" } fn description(&self) -> &str { "Reverses the LazyFrame" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Reverses the dataframe.", example: "[[a b]; [6 2] [4 2] [2 2]] | polars into-df | polars reverse", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(2), Value::test_int(4), Value::test_int(6)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(2), Value::test_int(2)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let lazy = NuLazyFrame::try_from_pipeline_coerce(plugin, input, call.head) .map_err(LabeledError::from)?; let lazy = NuLazyFrame::new(lazy.from_eager, lazy.to_polars().reverse()); lazy.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; use nu_protocol::ShellError; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&LazyReverse) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/select.rs
crates/nu_plugin_polars/src/dataframe/command/data/select.rs
use crate::{ PolarsPlugin, dataframe::values::{Column, NuDataFrame, NuExpression, NuLazyFrame}, values::{CustomValueSupport, PolarsPluginType}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, Signature, Span, SyntaxShape, Value, }; #[derive(Clone)] pub struct LazySelect; impl PluginCommand for LazySelect { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars select" } fn description(&self) -> &str { "Selects columns from lazyframe." } fn signature(&self) -> Signature { Signature::build(self.name()) .rest( "select expressions", SyntaxShape::Any, "Expression(s) that define the column selection", ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Select a column from the dataframe", example: "[[a b]; [6 2] [4 2] [2 2]] | polars into-df | polars select a", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "a".to_string(), vec![Value::test_int(6), Value::test_int(4), Value::test_int(2)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Select a column from a dataframe using a record", example: "[[a b]; [6 2] [4 2] [2 2]] | polars into-df | polars select {c: ((polars col a) * 2)}", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "c".to_string(), vec![Value::test_int(12), Value::test_int(8), Value::test_int(4)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Select a column from a dataframe using a mix of expressions and record of expressions", example: "[[a b]; [6 2] [4 2] [2 2]] | polars into-df | polars select a b {c: ((polars col a) ** 2)}", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(6), Value::test_int(4), Value::test_int(2)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(2), Value::test_int(2)], ), Column::new( "c".to_string(), vec![Value::test_int(36), Value::test_int(16), Value::test_int(4)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let vals: Vec<Value> = call.rest(0)?; let expr_value = Value::list(vals, call.head); let expressions = NuExpression::extract_exprs(plugin, expr_value)?; let pipeline_value = input.into_value(call.head)?; let lazy = NuLazyFrame::try_from_value_coerce(plugin, &pipeline_value)?; let lazy: NuLazyFrame = lazy.to_polars().select(&expressions).into(); lazy.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { test_polars_plugin_command(&LazySelect) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/pivot.rs
crates/nu_plugin_polars/src/dataframe/command/data/pivot.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use chrono::DateTime; use polars::prelude::Expr; use polars_lazy::frame::pivot::{pivot, pivot_stable}; use crate::{ PolarsPlugin, dataframe::values::utils::convert_columns_string, values::{Column, CustomValueSupport, NuExpression, PolarsPluginObject, PolarsPluginType}, }; use crate::values::NuDataFrame; #[derive(Clone)] pub struct PivotDF; impl PluginCommand for PivotDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars pivot" } fn description(&self) -> &str { "Pivot a DataFrame from long to wide format." } fn signature(&self) -> Signature { Signature::build(self.name()) .required_named( "on", SyntaxShape::List(Box::new(SyntaxShape::String)), "column names for pivoting", Some('o'), ) .required_named( "index", SyntaxShape::List(Box::new(SyntaxShape::String)), "column names for indexes", Some('i'), ) .required_named( "values", SyntaxShape::List(Box::new(SyntaxShape::String)), "column names used as value columns", Some('v'), ) .named( "aggregate", SyntaxShape::Any, "Aggregation to apply when pivoting. The following are supported: first, sum, min, max, mean, median, count, last, or a custom expression", Some('a'), ) .named( "separator", SyntaxShape::String, "Delimiter in generated column names in case of multiple `values` columns (default '_')", Some('p'), ) .switch( "sort", "Sort columns", Some('s'), ) .switch( "streamable", "Whether or not to use the polars streaming engine. Only valid for lazy dataframes", Some('t'), ) .switch( "stable", "Perform a stable pivot.", None, ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Perform a pivot in order to show individuals test score by subject", example: "[[name subject date test_1 test_2]; [Cady maths 2025-04-01 98 100] [Cady physics 2025-04-01 99 100] [Karen maths 2025-04-02 61 60] [Karen physics 2025-04-02 58 60]] | polars into-df | polars pivot --on [subject] --index [name date] --values [test_1]", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "name".to_string(), vec![ Value::string("Cady", Span::test_data()), Value::string("Karen", Span::test_data()), ], ), Column::new( "date".to_string(), vec![ Value::date( DateTime::parse_from_str( "2025-04-01 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2025-04-02 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), ], ), Column::new( "maths".to_string(), vec![ Value::int(98, Span::test_data()), Value::int(61, Span::test_data()), ], ), Column::new( "physics".to_string(), vec![ Value::int(99, Span::test_data()), Value::int(58, Span::test_data()), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::unknown()), ), }, Example { description: "Perform a pivot with multiple `values` columns with a separator", example: "[[name subject date test_1 test_2 grade_1 grade_2]; [Cady maths 2025-04-01 98 100 A A] [Cady physics 2025-04-01 99 100 A A] [Karen maths 2025-04-02 61 60 D D] [Karen physics 2025-04-02 58 60 D D]] | polars into-df | polars pivot --on [subject] --index [name] --values [test_1 grade_1] --separator /", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "name".to_string(), vec![ Value::string("Cady", Span::test_data()), Value::string("Karen", Span::test_data()), ], ), Column::new( "test_1/maths".to_string(), vec![ Value::int(98, Span::test_data()), Value::int(61, Span::test_data()), ], ), Column::new( "test_1/physics".to_string(), vec![ Value::int(99, Span::test_data()), Value::int(58, Span::test_data()), ], ), Column::new( "grade_1/maths".to_string(), vec![ Value::string("A", Span::test_data()), Value::string("D", Span::test_data()), ], ), Column::new( "grade_1/physics".to_string(), vec![ Value::string("A", Span::test_data()), Value::string("D", Span::test_data()), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::unknown()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); match PolarsPluginObject::try_from_pipeline(plugin, input, call.head)? { PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => { command_eager(plugin, engine, call, lazy.collect(call.head)?) } _ => Err(ShellError::GenericError { error: "Must be a dataframe or lazy dataframe".into(), msg: "".into(), span: Some(call.head), help: None, inner: vec![], }), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let on_col: Vec<Value> = call.get_flag("on")?.expect("required value"); let index_col: Vec<Value> = call.get_flag("index")?.expect("required value"); let val_col: Vec<Value> = call.get_flag("values")?.expect("required value"); let (on_col_string, ..) = convert_columns_string(on_col, call.head)?; let (index_col_string, ..) = convert_columns_string(index_col, call.head)?; let (val_col_string, ..) = convert_columns_string(val_col, call.head)?; let aggregate: Option<Expr> = call .get_flag::<Value>("aggregate")? .map(|val| pivot_agg_for_value(plugin, val)) .transpose()?; let separator: Option<String> = call.get_flag::<String>("separator")?; let sort = call.has_flag("sort")?; let stable = call.has_flag("stable")?; let polars_df = df.to_polars(); let pivoted = if stable { pivot_stable( &polars_df, &on_col_string, Some(&index_col_string), Some(&val_col_string), sort, aggregate, separator.as_deref(), ) } else { pivot( &polars_df, &on_col_string, Some(&index_col_string), Some(&val_col_string), sort, aggregate, separator.as_deref(), ) } .map_err(|e| ShellError::GenericError { error: format!("Pivot error: {e}"), msg: "".into(), span: Some(call.head), help: None, inner: vec![], })?; let res = NuDataFrame::new(false, pivoted); res.to_pipeline_data(plugin, engine, call.head) } #[allow(dead_code)] fn check_column_datatypes<T: AsRef<str>>( df: &polars::prelude::DataFrame, cols: &[T], col_span: Span, ) -> Result<(), ShellError> { if cols.is_empty() { return Err(ShellError::GenericError { error: "Merge error".into(), msg: "empty column list".into(), span: Some(col_span), help: None, inner: vec![], }); } // Checking if they are same type if cols.len() > 1 { for w in cols.windows(2) { let l_series = df .column(w[0].as_ref()) .map_err(|e| ShellError::GenericError { error: "Error selecting columns".into(), msg: e.to_string(), span: Some(col_span), help: None, inner: vec![], })?; let r_series = df .column(w[1].as_ref()) .map_err(|e| ShellError::GenericError { error: "Error selecting columns".into(), msg: e.to_string(), span: Some(col_span), help: None, inner: vec![], })?; if l_series.dtype() != r_series.dtype() { return Err(ShellError::GenericError { error: "Merge error".into(), msg: "found different column types in list".into(), span: Some(col_span), help: Some(format!( "datatypes {} and {} are incompatible", l_series.dtype(), r_series.dtype() )), inner: vec![], }); } } } Ok(()) } fn pivot_agg_for_value(plugin: &PolarsPlugin, agg: Value) -> Result<Expr, ShellError> { match agg { Value::String { val, .. } => match val.as_str() { "first" => Ok(polars::prelude::first().as_expr()), "sum" => Ok(polars::prelude::sum("*")), "min" => Ok(polars::prelude::min("*")), "max" => Ok(polars::prelude::max("*")), "mean" => Ok(polars::prelude::mean("*")), "median" => Ok(polars::prelude::median("*")), "count" => Ok(polars::prelude::len()), "len" => Ok(polars::prelude::len()), "last" => Ok(polars::prelude::last().as_expr()), s => Err(ShellError::GenericError { error: format!("{s} is not a valid aggregation"), msg: "".into(), span: None, help: Some( "Use one of the following: first, sum, min, max, mean, median, count, last" .into(), ), inner: vec![], }), }, Value::Custom { .. } => { let expr = NuExpression::try_from_value(plugin, &agg)?; Ok(expr.into_polars()) } _ => Err(ShellError::GenericError { error: "Aggregation must be a string or expression".into(), msg: "".into(), span: Some(agg.span()), help: None, inner: vec![], }), } } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&PivotDF) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/sort_by_expr.rs
crates/nu_plugin_polars/src/dataframe/command/data/sort_by_expr.rs
use crate::values::{NuLazyFrame, PolarsPluginType}; use crate::{ PolarsPlugin, dataframe::values::{Column, NuDataFrame, NuExpression}, values::CustomValueSupport, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::chunked_array::ops::SortMultipleOptions; #[derive(Clone)] pub struct LazySortBy; impl PluginCommand for LazySortBy { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars sort-by" } fn description(&self) -> &str { "Sorts a lazy dataframe based on expression(s)." } fn signature(&self) -> Signature { Signature::build(self.name()) .rest( "sort expression", SyntaxShape::Any, "sort expression for the dataframe", ) .named( "reverse", SyntaxShape::List(Box::new(SyntaxShape::Boolean)), "Reverse sorting. Default is false", Some('r'), ) .switch( "nulls-last", "nulls are shown last in the dataframe", Some('n'), ) .switch("maintain-order", "Maintains order during sort", Some('m')) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Sort dataframe by one column", example: "[[a b]; [6 2] [1 4] [4 1]] | polars into-df | polars sort-by a", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(4), Value::test_int(6)], ), Column::new( "b".to_string(), vec![Value::test_int(4), Value::test_int(1), Value::test_int(2)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Sort column using two columns", example: "[[a b]; [6 2] [1 1] [1 4] [2 4]] | polars into-df | polars sort-by [a b] -r [false true]", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![ Value::test_int(1), Value::test_int(1), Value::test_int(2), Value::test_int(6), ], ), Column::new( "b".to_string(), vec![ Value::test_int(4), Value::test_int(1), Value::test_int(4), Value::test_int(2), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let vals: Vec<Value> = call.rest(0)?; let expr_value = Value::list(vals, call.head); let expressions = NuExpression::extract_exprs(plugin, expr_value)?; let nulls_last = call.has_flag("nulls-last")?; let maintain_order = call.has_flag("maintain-order")?; let reverse: Option<Vec<bool>> = call.get_flag("reverse")?; let reverse = match reverse { Some(list) => { if expressions.len() != list.len() { let span = call .get_flag::<Value>("reverse")? .expect("already checked and it exists") .span(); Err(ShellError::GenericError { error: "Incorrect list size".into(), msg: "Size doesn't match expression list".into(), span: Some(span), help: None, inner: vec![], })? } else { list } } None => expressions.iter().map(|_| false).collect::<Vec<bool>>(), }; let sort_options = SortMultipleOptions { descending: reverse, nulls_last: vec![nulls_last], multithreaded: true, maintain_order, // Applying a limit here will result in a panic // it is not supported by polars in this context limit: None, }; let pipeline_value = input.into_value(call.head)?; let lazy = NuLazyFrame::try_from_value_coerce(plugin, &pipeline_value)?; let lazy = NuLazyFrame::new( lazy.from_eager, lazy.to_polars().sort_by_exprs(&expressions, sort_options), ); lazy.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&LazySortBy) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/collect.rs
crates/nu_plugin_polars/src/dataframe/command/data/collect.rs
use crate::{ Cacheable, PolarsPlugin, dataframe::values::{Column, NuDataFrame}, values::{CustomValueSupport, PolarsPluginObject, PolarsPluginType, cant_convert_err}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; #[derive(Clone)] pub struct LazyCollect; impl PluginCommand for LazyCollect { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars collect" } fn description(&self) -> &str { "Collect lazy dataframe into eager dataframe." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ]) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "drop duplicates", example: "[[a b]; [1 2] [3 4]] | polars into-lazy | polars collect", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(3)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(4)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuLazyFrame(lazy) => { let mut eager = lazy.collect(call.head)?; // We don't want this converted back to a lazy frame eager.from_lazy = true; Ok(PipelineData::value( eager .cache(plugin, engine, call.head)? .into_value(call.head), None, )) } PolarsPluginObject::NuDataFrame(df) => { // This should just increment the cache value. // We can return a value back without incrementing the // cache value or the value will be dropped (issue #12828) let cv = plugin .cache .get(&df.id, true)? .ok_or_else(|| ShellError::GenericError { error: format!("Failed to get cached value {}", df.id), msg: "".into(), span: Some(call.head), help: None, inner: vec![], })?; let df = NuDataFrame::from_cache_value(cv.value.clone())?; // just return the dataframe, add to cache again to be safe Ok(PipelineData::value(df.into_value(call.head), None)) } _ => Err(cant_convert_err( &value, &[PolarsPluginType::NuLazyFrame, PolarsPluginType::NuDataFrame], )), } .map_err(LabeledError::from) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { test_polars_plugin_command(&LazyCollect) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/filter.rs
crates/nu_plugin_polars/src/dataframe/command/data/filter.rs
use crate::{ PolarsPlugin, dataframe::values::{Column, NuDataFrame, NuExpression, NuLazyFrame}, values::{CustomValueSupport, PolarsPluginObject, PolarsPluginType, cant_convert_err}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; #[derive(Clone)] pub struct LazyFilter; impl PluginCommand for LazyFilter { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars filter" } fn description(&self) -> &str { "Filter dataframe based in expression." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "filter expression", SyntaxShape::Any, "Expression that define the column selection", ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Filter dataframe using an expression", example: "[[a b]; [6 2] [4 2] [2 2]] | polars into-df | polars filter ((polars col a) >= 4)", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(6), Value::test_int(4)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(2)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Filter dataframe for rows where dt is within the last 2 days of the maximum dt value", example: "[[dt val]; [2025-04-01 1] [2025-04-02 2] [2025-04-03 3] [2025-04-04 4]] | polars into-df | polars filter ((polars col dt) > ((polars col dt | polars max | $in - 2day)))", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "dt".to_string(), vec![ Value::date( chrono::DateTime::parse_from_str( "2025-04-03 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( chrono::DateTime::parse_from_str( "2025-04-04 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), ], ), Column::new( "val".to_string(), vec![Value::test_int(3), Value::test_int(4)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Filter a single column in a group-by context", example: "[[a b]; [foo 1] [foo 2] [foo 3] [bar 2] [bar 3] [bar 4]] | polars into-df | polars group-by a --maintain-order | polars agg { lt: (polars col b | polars filter ((polars col b) < 2) | polars sum) gte: (polars col b | polars filter ((polars col b) >= 3) | polars sum) } | polars collect", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_string("foo"), Value::test_string("bar")], ), Column::new( "lt".to_string(), vec![Value::test_int(1), Value::test_int(0)], ), Column::new( "gte".to_string(), vec![Value::test_int(3), Value::test_int(7)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let expr_value: Value = call.req(0)?; let filter_expr = NuExpression::try_from_value(plugin, &expr_value)?; let pipeline_value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &pipeline_value)? { PolarsPluginObject::NuDataFrame(df) => { command(plugin, engine, call, df.lazy(), filter_expr) } PolarsPluginObject::NuLazyFrame(lazy) => { command(plugin, engine, call, lazy, filter_expr) } PolarsPluginObject::NuExpression(expr) => { let res: NuExpression = expr.into_polars().filter(filter_expr.into_polars()).into(); res.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &pipeline_value, &[ // PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyGroupBy, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, filter_expr: NuExpression, ) -> Result<PipelineData, ShellError> { let lazy = NuLazyFrame::new( lazy.from_eager, lazy.to_polars().filter(filter_expr.into_polars()), ); lazy.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&LazyFilter) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/rename.rs
crates/nu_plugin_polars/src/dataframe/command/data/rename.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use crate::{ PolarsPlugin, dataframe::{utils::extract_strings, values::NuLazyFrame}, values::{CustomValueSupport, PolarsPluginObject, PolarsPluginType}, }; use crate::values::{Column, NuDataFrame}; #[derive(Clone)] pub struct RenameDF; impl PluginCommand for RenameDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars rename" } fn description(&self) -> &str { "Rename a dataframe column." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "columns", SyntaxShape::Any, "Column(s) to be renamed. A string or list of strings", ) .required( "new names", SyntaxShape::Any, "New names for the selected column(s). A string or list of strings", ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe or lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Renames a series", example: "[5 6 7 8] | polars into-df | polars rename '0' new_name", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "new_name".to_string(), vec![ Value::test_int(5), Value::test_int(6), Value::test_int(7), Value::test_int(8), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Renames a dataframe column", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars rename a a_new", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a_new".to_string(), vec![Value::test_int(1), Value::test_int(3)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(4)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Renames two dataframe columns", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars rename [a b] [a_new b_new]", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a_new".to_string(), vec![Value::test_int(1), Value::test_int(3)], ), Column::new( "b_new".to_string(), vec![Value::test_int(2), Value::test_int(4)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value).map_err(LabeledError::from)? { PolarsPluginObject::NuDataFrame(df) => { command_eager(plugin, engine, call, df).map_err(LabeledError::from) } PolarsPluginObject::NuLazyFrame(lazy) => { command_lazy(plugin, engine, call, lazy).map_err(LabeledError::from) } _ => Err(LabeledError::new(format!("Unsupported type: {value:?}")) .with_label("Unsupported Type", call.head)), } .map(|pd| pd.set_metadata(metadata)) } } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let columns: Value = call.req(0)?; let columns = extract_strings(columns)?; let new_names: Value = call.req(1)?; let new_names = extract_strings(new_names)?; let mut polars_df = df.to_polars(); for (from, to) in columns.iter().zip(new_names.iter()) { polars_df .rename(from, to.into()) .map_err(|e| ShellError::GenericError { error: "Error renaming".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; } let df = NuDataFrame::new(false, polars_df); df.to_pipeline_data(plugin, engine, call.head) } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let columns: Value = call.req(0)?; let columns = extract_strings(columns)?; let new_names: Value = call.req(1)?; let new_names = extract_strings(new_names)?; if columns.len() != new_names.len() { let value: Value = call.req(1)?; return Err(ShellError::IncompatibleParametersSingle { msg: "New name list has different size to column list".into(), span: value.span(), }); } let lazy = lazy.to_polars(); let lazy: NuLazyFrame = lazy.rename(&columns, &new_names, true).into(); lazy.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&RenameDF) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/take.rs
crates/nu_plugin_polars/src/dataframe/command/data/take.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::prelude::DataType; use crate::{PolarsPlugin, dataframe::values::Column, values::CustomValueSupport}; use crate::values::{NuDataFrame, PolarsPluginType}; #[derive(Clone)] pub struct TakeDF; impl PluginCommand for TakeDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars take" } fn description(&self) -> &str { "Creates new dataframe using the given indices." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "indices", SyntaxShape::Any, "list of indices used to take data", ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Takes selected rows from dataframe", example: r#"let df = ([[a b]; [4 1] [5 2] [4 3]] | polars into-df); let indices = ([0 2] | polars into-df); $df | polars take $indices"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(4), Value::test_int(4)], ), Column::new( "b".to_string(), vec![Value::test_int(1), Value::test_int(3)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Takes selected rows from series", example: r#"let series = ([4 1 5 2 4 3] | polars into-df); let indices = ([0 2] | polars into-df); $series | polars take $indices"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![Value::test_int(4), Value::test_int(5)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let index_value: Value = call.req(0)?; let index_span = index_value.span(); let index = NuDataFrame::try_from_value_coerce(plugin, &index_value, call.head)? .as_series(index_span)?; let casted = match index.dtype() { DataType::UInt32 | DataType::UInt64 | DataType::Int32 | DataType::Int64 => index .cast(&DataType::UInt64) .map_err(|e| ShellError::GenericError { error: "Error casting index list".into(), msg: e.to_string(), span: Some(index_span), help: None, inner: vec![], }), _ => Err(ShellError::GenericError { error: "Incorrect type".into(), msg: "Series with incorrect type".into(), span: Some(call.head), help: Some("Consider using a Series with type int type".into()), inner: vec![], }), }?; let indices = casted.u64().map_err(|e| ShellError::GenericError { error: "Error casting index list".into(), msg: e.to_string(), span: Some(index_span), help: None, inner: vec![], })?; let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let polars_df = df .to_polars() .take(indices) .map_err(|e| ShellError::GenericError { error: "Error taking values".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let df = NuDataFrame::new(df.from_lazy, polars_df); df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&TakeDF) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/struct_json_encode.rs
crates/nu_plugin_polars/src/dataframe/command/data/struct_json_encode.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, Signature, Span, Type}; use polars::df; use crate::{ PolarsPlugin, values::{CustomValueSupport, NuDataFrame, NuExpression}, }; #[derive(Clone)] pub struct StructJsonEncode; impl PluginCommand for StructJsonEncode { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars struct-json-encode" } fn description(&self) -> &str { "Convert this struct to a string column with json values." } fn signature(&self) -> Signature { Signature::build(self.name()) .category(Category::Custom("dataframe".into())) .input_output_type(Type::custom("expression"), Type::custom("expression")) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Encode a struct as JSON", example: r#"[[id person]; [1 {name: "Bob", age: 36}] [2 {name: "Betty", age: 63}]] | polars into-df -s {id: i32, person: {name: str, age: u8}} | polars select id (polars col person | polars struct-json-encode | polars as encoded) | polars sort-by id | polars collect"#, result: Some( NuDataFrame::from( df!( "id" => [1i32, 2], "encoded" => [ r#"{"name":"Bob","age":36}"#, r#"{"name":"Betty","age":63}"#, ], ) .expect("Should be able to create a simple dataframe"), ) .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { NuExpression::try_from_pipeline(plugin, input, call.head) .map(|expr| expr.into_polars().struct_().json_encode()) .map(NuExpression::from) .and_then(|expr| expr.to_pipeline_data(plugin, engine, call.head)) .map_err(LabeledError::from) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/arg_where.rs
crates/nu_plugin_polars/src/dataframe/command/data/arg_where.rs
use crate::{ PolarsPlugin, dataframe::values::{Column, NuDataFrame, NuExpression}, values::{CustomValueSupport, PolarsPluginType}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, Signature, Span, SyntaxShape, Type, Value, }; use polars::prelude::arg_where; #[derive(Clone)] pub struct ExprArgWhere; impl PluginCommand for ExprArgWhere { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars arg-where" } fn description(&self) -> &str { "Creates an expression that returns the arguments where expression is true." } fn signature(&self) -> Signature { Signature::build(self.name()) .required("column name", SyntaxShape::Any, "Expression to evaluate") .input_output_type(Type::Any, PolarsPluginType::NuExpression.into()) .category(Category::Custom("expression".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Return a dataframe where the value match the expression", example: "let df = ([[a b]; [one 1] [two 2] [three 3]] | polars into-df); $df | polars select (polars arg-where ((polars col b) >= 2) | polars as b_arg)", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "b_arg".to_string(), vec![Value::test_int(1), Value::test_int(2)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn search_terms(&self) -> Vec<&str> { vec!["condition", "match", "if"] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value: Value = call.req(0)?; let expr = NuExpression::try_from_value(plugin, &value)?; let expr: NuExpression = arg_where(expr.into_polars()).into(); expr.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { test_polars_plugin_command(&ExprArgWhere) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/unique.rs
crates/nu_plugin_polars/src/dataframe/command/data/unique.rs
use crate::{ PolarsPlugin, dataframe::{utils::extract_strings, values::NuLazyFrame}, values::{ CustomValueSupport, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use crate::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::prelude::{IntoSeries, UniqueKeepStrategy, cols}; #[derive(Clone)] pub struct Unique; impl PluginCommand for Unique { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars unique" } fn description(&self) -> &str { "Returns unique values from a dataframe." } fn signature(&self) -> Signature { Signature::build(self.name()) .named( "subset", SyntaxShape::Any, "Subset of column(s) to use to maintain rows (lazy df)", Some('s'), ) .switch( "last", "Keeps last unique value. Default keeps first value (lazy df)", Some('l'), ) .switch( "maintain-order", "Keep the same order as the original DataFrame (lazy df)", Some('k'), ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe or lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns unique values from a series", example: "[2 2 2 2 2] | polars into-df | polars unique", result: Some( NuDataFrame::try_from_columns( vec![Column::new("0".to_string(), vec![Value::test_int(2)])], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns unique values in a subset of lazyframe columns", example: "[[a b c]; [1 2 1] [2 2 2] [3 2 1]] | polars into-lazy | polars unique --subset [b c] | polars collect", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(2)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(2)], ), Column::new( "c".to_string(), vec![Value::test_int(1), Value::test_int(2)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns unique values in a subset of lazyframe columns", example: r#"[[a b c]; [1 2 1] [2 2 2] [3 2 1]] | polars into-lazy | polars unique --subset [b c] --last | polars collect"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(2), Value::test_int(3)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(2)], ), Column::new( "c".to_string(), vec![Value::test_int(2), Value::test_int(1)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns unique values in a subset of lazyframe columns", example: r#"[[a]; [2] [1] [2]] | polars into-lazy | polars select (polars col a | polars unique) | polars collect"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(2)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns unique values in a subset of lazyframe columns", example: r#"[[a]; [2] [1] [2]] | polars into-lazy | polars select (polars col a | polars unique --maintain-order) | polars collect"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "a".to_string(), vec![Value::test_int(2), Value::test_int(1)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuExpression(expr) => { let maintain = call.has_flag("maintain-order")?; let res: NuExpression = if maintain { expr.into_polars().unique_stable().into() } else { expr.into_polars().unique().into() }; res.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyGroupBy, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let series = df.as_series(call.head)?; let res = series.unique().map_err(|e| ShellError::GenericError { error: "Error calculating unique values".into(), msg: e.to_string(), span: Some(call.head), help: Some("The str-slice command can only be used with string columns".into()), inner: vec![], })?; let df = NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let last = call.has_flag("last")?; let maintain = call.has_flag("maintain-order")?; // todo: allow selectors to be passed in let subset: Option<Value> = call.get_flag("subset")?; let subset = match subset { Some(value) => Some(cols(extract_strings(value)?)), None => None, }; let strategy = if last { UniqueKeepStrategy::Last } else { UniqueKeepStrategy::First }; let lazy = lazy.to_polars(); let lazy: NuLazyFrame = if maintain { lazy.unique(subset, strategy).into() } else { lazy.unique_stable(subset, strategy).into() }; lazy.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&Unique) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/sql_expr.rs
crates/nu_plugin_polars/src/dataframe/command/data/sql_expr.rs
use polars::error::PolarsError; use polars::prelude::{DataType, Expr, LiteralValue, PolarsResult as Result, TimeUnit, col, lit}; use sqlparser::ast::{ ArrayElemTypeDef, BinaryOperator as SQLBinaryOperator, DataType as SQLDataType, DuplicateTreatment, Expr as SqlExpr, Function as SQLFunction, FunctionArguments, Value as SqlValue, WindowType, }; fn map_sql_polars_datatype(data_type: &SQLDataType) -> Result<DataType> { Ok(match data_type { SQLDataType::Char(_) | SQLDataType::Varchar(_) | SQLDataType::Uuid | SQLDataType::Clob(_) | SQLDataType::Text | SQLDataType::String(_) => DataType::String, SQLDataType::Float(_) => DataType::Float32, SQLDataType::Real => DataType::Float32, SQLDataType::Double => DataType::Float64, SQLDataType::TinyInt(_) => DataType::Int8, SQLDataType::UnsignedTinyInt(_) => DataType::UInt8, SQLDataType::SmallInt(_) => DataType::Int16, SQLDataType::UnsignedSmallInt(_) => DataType::UInt16, SQLDataType::Int(_) => DataType::Int32, SQLDataType::UnsignedInt(_) => DataType::UInt32, SQLDataType::BigInt(_) => DataType::Int64, SQLDataType::UnsignedBigInt(_) => DataType::UInt64, SQLDataType::Boolean => DataType::Boolean, SQLDataType::Date => DataType::Date, SQLDataType::Time(_, _) => DataType::Time, SQLDataType::Timestamp(_, _) => DataType::Datetime(TimeUnit::Microseconds, None), SQLDataType::Interval => DataType::Duration(TimeUnit::Microseconds), SQLDataType::Array(array_type_def) => match array_type_def { ArrayElemTypeDef::AngleBracket(inner_type) | ArrayElemTypeDef::SquareBracket(inner_type, _) => { DataType::List(Box::new(map_sql_polars_datatype(inner_type)?)) } _ => { return Err(PolarsError::ComputeError( "SQL Datatype Array(None) was not supported in polars-sql yet!".into(), )); } }, _ => { return Err(PolarsError::ComputeError( format!("SQL Datatype {data_type:?} was not supported in polars-sql yet!").into(), )); } }) } fn cast_(expr: Expr, data_type: &SQLDataType) -> Result<Expr> { let polars_type = map_sql_polars_datatype(data_type)?; Ok(expr.cast(polars_type)) } fn binary_op_(left: Expr, right: Expr, op: &SQLBinaryOperator) -> Result<Expr> { Ok(match op { SQLBinaryOperator::Plus => left + right, SQLBinaryOperator::Minus => left - right, SQLBinaryOperator::Multiply => left * right, SQLBinaryOperator::Divide => left / right, SQLBinaryOperator::Modulo => left % right, SQLBinaryOperator::StringConcat => { left.cast(DataType::String) + right.cast(DataType::String) } SQLBinaryOperator::Gt => left.gt(right), SQLBinaryOperator::Lt => left.lt(right), SQLBinaryOperator::GtEq => left.gt_eq(right), SQLBinaryOperator::LtEq => left.lt_eq(right), SQLBinaryOperator::Eq => left.eq(right), SQLBinaryOperator::NotEq => left.eq(right).not(), SQLBinaryOperator::And => left.and(right), SQLBinaryOperator::Or => left.or(right), SQLBinaryOperator::Xor => left.xor(right), _ => { return Err(PolarsError::ComputeError( format!("SQL Operator {op:?} was not supported in polars-sql yet!").into(), )); } }) } fn literal_expr(value: &SqlValue) -> Result<Expr> { Ok(match value { SqlValue::Number(s, _) => { // Check for existence of decimal separator dot if s.contains('.') { s.parse::<f64>().map(lit).map_err(|_| { PolarsError::ComputeError(format!("Can't parse literal {s:?}").into()) }) } else { s.parse::<i64>().map(lit).map_err(|_| { PolarsError::ComputeError(format!("Can't parse literal {s:?}").into()) }) }? } SqlValue::SingleQuotedString(s) => lit(s.clone()), SqlValue::NationalStringLiteral(s) => lit(s.clone()), SqlValue::HexStringLiteral(s) => lit(s.clone()), SqlValue::DoubleQuotedString(s) => lit(s.clone()), SqlValue::Boolean(b) => lit(*b), SqlValue::Null => Expr::Literal(LiteralValue::untyped_null()), _ => { return Err(PolarsError::ComputeError( format!("Parsing SQL Value {value:?} was not supported in polars-sql yet!").into(), )); } }) } pub fn parse_sql_expr(expr: &SqlExpr) -> Result<Expr> { Ok(match expr { SqlExpr::Identifier(e) => col(&e.value), SqlExpr::BinaryOp { left, op, right } => { let left = parse_sql_expr(left)?; let right = parse_sql_expr(right)?; binary_op_(left, right, op)? } SqlExpr::Function(sql_function) => parse_sql_function(sql_function)?, SqlExpr::Cast { expr, data_type, .. } => cast_(parse_sql_expr(expr)?, data_type)?, SqlExpr::Nested(expr) => parse_sql_expr(expr)?, SqlExpr::Value(value) => literal_expr(value)?, _ => { return Err(PolarsError::ComputeError( format!("Expression: {expr:?} was not supported in polars-sql yet!").into(), )); } }) } fn apply_window_spec(expr: Expr, window_type: Option<&WindowType>) -> Result<Expr> { Ok(match &window_type { Some(wtype) => match wtype { WindowType::WindowSpec(window_spec) => { // Process for simple window specification, partition by first let partition_by = window_spec .partition_by .iter() .map(parse_sql_expr) .collect::<Result<Vec<_>>>()?; expr.over(partition_by) // Order by and Row range may not be supported at the moment } // TODO: make NamedWindow work WindowType::NamedWindow(_named) => { return Err(PolarsError::ComputeError( format!("Expression: {expr:?} was not supported in polars-sql yet!").into(), )); } }, None => expr, }) } fn parse_sql_function(sql_function: &SQLFunction) -> Result<Expr> { use sqlparser::ast::{FunctionArg, FunctionArgExpr}; // Function name mostly do not have name space, so it mostly take the first args let function_name = sql_function.name.0[0].value.to_ascii_lowercase(); // One day this should support the additional argument types supported with 0.40 let (args, distinct) = match &sql_function.args { FunctionArguments::List(list) => ( list.args.clone(), list.duplicate_treatment == Some(DuplicateTreatment::Distinct), ), _ => (vec![], false), }; let args = args .iter() .map(|arg| match arg { FunctionArg::Named { arg, .. } => arg, FunctionArg::Unnamed(arg) => arg, FunctionArg::ExprNamed { arg, .. } => arg, }) .collect::<Vec<_>>(); Ok(match (function_name.as_str(), args.as_slice(), distinct) { ("sum", [FunctionArgExpr::Expr(expr)], false) => { apply_window_spec(parse_sql_expr(expr)?, sql_function.over.as_ref())?.sum() } ("count", [FunctionArgExpr::Expr(expr)], false) => { apply_window_spec(parse_sql_expr(expr)?, sql_function.over.as_ref())?.count() } ("count", [FunctionArgExpr::Expr(expr)], true) => { apply_window_spec(parse_sql_expr(expr)?, sql_function.over.as_ref())?.n_unique() } // Special case for wildcard args to count function. ("count", [FunctionArgExpr::Wildcard], false) => lit(1i32).count(), _ => return Err(PolarsError::ComputeError( format!( "Function {function_name:?} with args {args:?} was not supported in polars-sql yet!" ) .into(), )), }) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/flatten.rs
crates/nu_plugin_polars/src/dataframe/command/data/flatten.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, Signature, Span, SyntaxShape, Value, }; use crate::{ PolarsPlugin, dataframe::values::{Column, NuDataFrame}, values::{CustomValueSupport, PolarsPluginType}, }; use super::explode::explode; #[derive(Clone)] pub struct LazyFlatten; impl PluginCommand for LazyFlatten { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars flatten" } fn description(&self) -> &str { "An alias for polars explode." } fn signature(&self) -> Signature { Signature::build(self.name()) .rest( "columns", SyntaxShape::String, "columns to flatten, only applicable for dataframes", ) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ]) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Flatten the specified dataframe", example: "[[id name hobbies]; [1 Mercy [Cycling Knitting]] [2 Bob [Skiing Football]]] | polars into-df | polars flatten hobbies | polars collect", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "id".to_string(), vec![ Value::test_int(1), Value::test_int(1), Value::test_int(2), Value::test_int(2), ], ), Column::new( "name".to_string(), vec![ Value::test_string("Mercy"), Value::test_string("Mercy"), Value::test_string("Bob"), Value::test_string("Bob"), ], ), Column::new( "hobbies".to_string(), vec![ Value::test_string("Cycling"), Value::test_string("Knitting"), Value::test_string("Skiing"), Value::test_string("Football"), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Select a column and flatten the values", example: "[[id name hobbies]; [1 Mercy [Cycling Knitting]] [2 Bob [Skiing Football]]] | polars into-df | polars select (polars col hobbies | polars flatten)", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "hobbies".to_string(), vec![ Value::test_string("Cycling"), Value::test_string("Knitting"), Value::test_string("Skiing"), Value::test_string("Football"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); explode(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { test_polars_plugin_command(&LazyFlatten) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/sql_context.rs
crates/nu_plugin_polars/src/dataframe/command/data/sql_context.rs
use crate::dataframe::command::data::sql_expr::parse_sql_expr; use polars::error::{ErrString, PolarsError}; use polars::prelude::{DataFrame, DataType, IntoLazy, LazyFrame, col}; use sqlparser::ast::{ Expr as SqlExpr, GroupByExpr, Select, SelectItem, SetExpr, Statement, TableFactor, Value as SQLValue, }; use sqlparser::dialect::GenericDialect; use sqlparser::parser::Parser; use std::collections::HashMap; #[derive(Default)] pub struct SQLContext { table_map: HashMap<String, LazyFrame>, dialect: GenericDialect, } impl SQLContext { pub fn new() -> Self { Self { table_map: HashMap::new(), dialect: GenericDialect, } } pub fn register(&mut self, name: &str, df: &DataFrame) { self.table_map.insert(name.to_owned(), df.clone().lazy()); } fn execute_select(&self, select_stmt: &Select) -> Result<LazyFrame, PolarsError> { // Determine involved dataframe // Implicit join require some more work in query parsers, Explicit join are preferred for now. let tbl = select_stmt.from.first().ok_or_else(|| { PolarsError::ComputeError(ErrString::from("No table found in select statement")) })?; let mut alias_map = HashMap::new(); let tbl_name = match &tbl.relation { TableFactor::Table { name, alias, .. } => { let tbl_name = name .0 .first() .ok_or_else(|| { PolarsError::ComputeError(ErrString::from( "No table found in select statement", )) })? .value .to_string(); if self.table_map.contains_key(&tbl_name) { if let Some(alias) = alias { alias_map.insert(alias.name.value.clone(), tbl_name.to_owned()); }; tbl_name } else { return Err(PolarsError::ComputeError( format!("Table name {tbl_name} was not found").into(), )); } } // Support bare table, optional with alias for now _ => return Err(PolarsError::ComputeError("Not implemented".into())), }; let df = &self.table_map[&tbl_name]; let mut raw_projection_before_alias: HashMap<String, usize> = HashMap::new(); let mut contain_wildcard = false; // Filter Expression let df = match select_stmt.selection.as_ref() { Some(expr) => { let filter_expression = parse_sql_expr(expr)?; df.clone().filter(filter_expression) } None => df.clone(), }; // Column Projections let projection = select_stmt .projection .iter() .enumerate() .map(|(i, select_item)| { Ok(match select_item { SelectItem::UnnamedExpr(expr) => { let expr = parse_sql_expr(expr)?; raw_projection_before_alias.insert(format!("{expr:?}"), i); expr } SelectItem::ExprWithAlias { expr, alias } => { let expr = parse_sql_expr(expr)?; raw_projection_before_alias.insert(format!("{expr:?}"), i); expr.alias(&alias.value) } SelectItem::QualifiedWildcard(_, _) | SelectItem::Wildcard(_) => { contain_wildcard = true; col("*") } }) }) .collect::<Result<Vec<_>, PolarsError>>()?; // Check for group by // After projection since there might be number. let group_by = match &select_stmt.group_by { GroupByExpr::All(_) => Err( PolarsError::ComputeError("Group-By Error: Only positive number or expression are supported, not all".into()) )?, GroupByExpr::Expressions(expressions, _) => expressions } .iter() .map( |e|match e { SqlExpr::Value(SQLValue::Number(idx, _)) => { let idx = match idx.parse::<usize>() { Ok(0)| Err(_) => Err( PolarsError::ComputeError( format!("Group-By Error: Only positive number or expression are supported, got {idx}").into() )), Ok(idx) => Ok(idx) }?; Ok(projection[idx].clone()) } SqlExpr::Value(_) => Err( PolarsError::ComputeError("Group-By Error: Only positive number or expression are supported".into()) ), _ => parse_sql_expr(e) } ) .collect::<Result<Vec<_>, PolarsError>>()?; let df = if group_by.is_empty() { df.select(projection) } else { // check groupby and projection due to difference between SQL and polars // Return error on wild card, shouldn't process this if contain_wildcard { return Err(PolarsError::ComputeError( "Group-By Error: Can't process wildcard in group-by".into(), )); } // Default polars group by will have group by columns at the front // need some container to contain position of group by columns and its position // at the final agg projection, check the schema for the existence of group by column // and its projections columns, keeping the original index let (exclude_expr, groupby_pos): (Vec<_>, Vec<_>) = group_by .iter() .map(|expr| raw_projection_before_alias.get(&format!("{expr:?}"))) .enumerate() .filter(|(_, proj_p)| proj_p.is_some()) .map(|(gb_p, proj_p)| (*proj_p.unwrap_or(&0), (*proj_p.unwrap_or(&0), gb_p))) .unzip(); let (agg_projection, agg_proj_pos): (Vec<_>, Vec<_>) = projection .iter() .enumerate() .filter(|(i, _)| !exclude_expr.contains(i)) .enumerate() .map(|(agg_pj, (proj_p, expr))| (expr.clone(), (proj_p, agg_pj + group_by.len()))) .unzip(); let agg_df = df.group_by(group_by).agg(agg_projection); let mut final_proj_pos = groupby_pos .into_iter() .chain(agg_proj_pos) .collect::<Vec<_>>(); final_proj_pos.sort_by(|(proj_pa, _), (proj_pb, _)| proj_pa.cmp(proj_pb)); let final_proj = final_proj_pos .into_iter() .map(|(_, shm_p)| { col(agg_df .clone() // FIXME: had to do this mess to get get_index to work, not sure why. need help .collect() .unwrap_or_default() .schema() .get_at_index(shm_p) .unwrap_or((&"".into(), &DataType::Null)) .0 .clone()) }) .collect::<Vec<_>>(); agg_df.select(final_proj) }; Ok(df) } pub fn execute(&self, query: &str) -> Result<LazyFrame, PolarsError> { let ast = Parser::parse_sql(&self.dialect, query) .map_err(|e| PolarsError::ComputeError(format!("{e:?}").into()))?; if ast.len() != 1 { Err(PolarsError::ComputeError( "One and only one statement at a time please".into(), )) } else { let ast = ast .first() .ok_or_else(|| PolarsError::ComputeError(ErrString::from("No statement found")))?; Ok(match ast { Statement::Query(query) => { let rs = match &*query.body { SetExpr::Select(select_stmt) => self.execute_select(select_stmt)?, _ => { return Err(PolarsError::ComputeError( "INSERT, UPDATE is not supported for polars".into(), )); } }; match &query.limit { Some(SqlExpr::Value(SQLValue::Number(nrow, _))) => { let nrow = nrow.parse().map_err(|err| { PolarsError::ComputeError( format!("Conversion Error: {err:?}").into(), ) })?; rs.limit(nrow) } None => rs, _ => { return Err(PolarsError::ComputeError( "Only support number argument to LIMIT clause".into(), )); } } } _ => { return Err(PolarsError::ComputeError( format!("Statement type {ast:?} is not supported").into(), )); } }) } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/filter_with.rs
crates/nu_plugin_polars/src/dataframe/command/data/filter_with.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::prelude::LazyFrame; use crate::{ PolarsPlugin, dataframe::values::{NuExpression, NuLazyFrame}, values::{CustomValueSupport, PolarsPluginObject, PolarsPluginType, cant_convert_err}, }; use crate::values::{Column, NuDataFrame}; #[derive(Clone)] pub struct FilterWith; impl PluginCommand for FilterWith { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars filter-with" } fn description(&self) -> &str { "Filters dataframe using a mask or expression as reference." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "mask or expression", SyntaxShape::Any, "boolean mask used to filter data", ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe or lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Filter dataframe using a bool mask", example: r#"let mask = ([true false] | polars into-df); [[a b]; [1 2] [3 4]] | polars into-df | polars filter-with $mask"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new("a".to_string(), vec![Value::test_int(1)]), Column::new("b".to_string(), vec![Value::test_int(2)]), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Filter dataframe using an expression", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars filter-with ((polars col a) > 1)", result: Some( NuDataFrame::try_from_columns( vec![ Column::new("a".to_string(), vec![Value::test_int(3)]), Column::new("b".to_string(), vec![Value::test_int(4)]), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), _ => Err(cant_convert_err( &value, &[PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let mask_value: Value = call.req(0)?; let mask_span = mask_value.span(); if NuExpression::can_downcast(&mask_value) { let expression = NuExpression::try_from_value(plugin, &mask_value)?; let lazy = df.lazy(); let lazy = lazy.apply_with_expr(expression, LazyFrame::filter); lazy.to_pipeline_data(plugin, engine, call.head) } else { let mask = NuDataFrame::try_from_value_coerce(plugin, &mask_value, mask_span)? .as_series(mask_span)?; let mask = mask.bool().map_err(|e| ShellError::GenericError { error: "Error casting to bool".into(), msg: e.to_string(), span: Some(mask_span), help: Some("Perhaps you want to use a series with booleans as mask".into()), inner: vec![], })?; let polars_df = df .as_ref() .filter(mask) .map_err(|e| ShellError::GenericError { error: "Error filtering dataframe".into(), msg: e.to_string(), span: Some(call.head), help: Some("The only allowed column types for dummies are String or Int".into()), inner: vec![], })?; let df = NuDataFrame::new(df.from_lazy, polars_df); df.to_pipeline_data(plugin, engine, call.head) } } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let expr: Value = call.req(0)?; let expr = NuExpression::try_from_value(plugin, &expr)?; let lazy = lazy.apply_with_expr(expr, LazyFrame::filter); lazy.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&FilterWith) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/unnest.rs
crates/nu_plugin_polars/src/dataframe/command/data/unnest.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, }; use polars::{df, prelude::PlSmallStr}; use crate::{ PolarsPlugin, values::{CustomValueSupport, NuLazyFrame, PolarsPluginObject, PolarsPluginType}, }; use crate::values::NuDataFrame; #[derive(Clone)] pub struct UnnestDF; impl PluginCommand for UnnestDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars unnest" } fn description(&self) -> &str { "Decompose struct columns into separate columns for each of their fields. The new columns will be inserted into the dataframe at the location of the struct column." } fn signature(&self) -> Signature { Signature::build(self.name()) .named( "separator", SyntaxShape::String, "optional separator to use when creating new column names", Some('s'), ) .rest("cols", SyntaxShape::String, "columns to unnest") .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Unnest a dataframe", example: r#"[[id person]; [1 {name: "Bob", age: 36}] [2 {name: "Betty", age: 63}]] | polars into-df -s {id: i64, person: {name: str, age: u8}} | polars unnest person | polars get id name age | polars sort-by id"#, result: Some( NuDataFrame::from( df!( "id" => [1, 2], "name" => ["Bob", "Betty"], "age" => [36, 63] ) .expect("Should be able to create a simple dataframe"), ) .into_value(Span::test_data()), ), }, Example { description: "Unnest a lazy dataframe", example: r#"[[id person]; [1 {name: "Bob", age: 36}] [2 {name: "Betty", age: 63}]] | polars into-df -s {id: i64, person: {name: str, age: u8}} | polars into-lazy | polars unnest person | polars select (polars col id) (polars col name) (polars col age) | polars collect | polars sort-by id"#, result: Some( NuDataFrame::from( df!( "id" => [1, 2], "name" => ["Bob", "Betty"], "age" => [36, 63] ) .expect("Should be able to create a simple dataframe"), ) .into_value(Span::test_data()), ), }, Example { description: "Unnest with a custom separator", example: r#"[[id person]; [1 {name: "Bob", age: 36}] [2 {name: "Betty", age: 63}]] | polars into-df -s {id: i64, person: {name: str, age: u8}} | polars unnest person -s "_" | polars get id person_name person_age | polars sort-by id"#, result: Some( NuDataFrame::from( df!( "id" => [1, 2], "person_name" => ["Bob", "Betty"], "person_age" => [36, 63] ) .expect("Should be able to create a simple dataframe"), ) .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); match PolarsPluginObject::try_from_pipeline(plugin, input, call.head)? { PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), _ => Err(ShellError::GenericError { error: "Must be a dataframe or lazy dataframe".into(), msg: "".into(), span: Some(call.head), help: None, inner: vec![], }), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let cols = call.rest::<String>(0)?; let separator = call.get_flag::<String>("separator")?; let polars = df.to_polars(); let result: NuDataFrame = polars .unnest(cols, separator.as_deref()) .map_err(|e| ShellError::GenericError { error: format!("Error unnesting dataframe: {e}"), msg: "".into(), span: Some(call.head), help: None, inner: vec![], })? .into(); result.to_pipeline_data(plugin, engine, call.head) } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let cols = call.rest::<String>(0)?; let separator = call.get_flag::<String>("separator")?.map(PlSmallStr::from); let polars = df.to_polars(); // todo - allow selectors to be passed in here let result: NuLazyFrame = polars.unnest(polars::prelude::cols(cols), separator).into(); result.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&UnnestDF) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/last.rs
crates/nu_plugin_polars/src/dataframe/command/data/last.rs
use crate::{ PolarsPlugin, values::{ Column, CustomValueSupport, NuLazyFrame, NuLazyGroupBy, PolarsPluginObject, PolarsPluginType, }, }; use crate::values::{NuDataFrame, NuExpression}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::df; const DEFAULT_ROWS: usize = 1; #[derive(Clone)] pub struct LastDF; impl PluginCommand for LastDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars last" } fn description(&self) -> &str { "Creates new dataframe with tail rows or creates a last expression." } fn signature(&self) -> Signature { Signature::build(self.name()) .optional("rows", SyntaxShape::Int, "Number of rows for tail") .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Create new dataframe with last rows", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars last 1", result: Some( NuDataFrame::try_from_columns( vec![ Column::new("a".to_string(), vec![Value::test_int(3)]), Column::new("b".to_string(), vec![Value::test_int(4)]), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Creates a last expression from a column", example: "polars col a | polars last", result: None, }, Example { description: "Aggregate the last values in the group.", example: "[[a b c d]; [1 0.5 true Apple] [2 0.5 true Orange] [2 4 true Apple] [3 10 false Apple] [4 13 false Banana] [5 14 true Banana]] | polars into-df -s {a: u8, b: f32, c: bool, d: str} | polars group-by d | polars last | polars sort-by [a] | polars collect", result: Some( NuDataFrame::new( false, df!( "d" => &["Orange", "Apple", "Banana"], "a" => &[2, 3, 5], "b" => &[0.50, 10.0, 14.0], "c" => &[true, false, true], ) .expect("dataframe creation should succeed"), ) .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => { command_eager(plugin, engine, call, df).map_err(|e| e.into()) } PolarsPluginObject::NuLazyFrame(lazy) => { command_lazy(plugin, engine, call, lazy).map_err(|e| e.into()) } PolarsPluginObject::NuLazyGroupBy(groupby) => { command_groupby(plugin, engine, call, groupby).map_err(|e| e.into()) } _ => { let expr = NuExpression::try_from_value(plugin, &value)?; let expr: NuExpression = expr.into_polars().last().into(); expr.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) } } .map(|pd| pd.set_metadata(metadata)) } } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let rows: Option<usize> = call.opt(0)?; let rows = rows.unwrap_or(DEFAULT_ROWS); let res = df.as_ref().tail(Some(rows)); let res = NuDataFrame::new(false, res); res.to_pipeline_data(plugin, engine, call.head) } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let rows: Option<u64> = call.opt(0)?; let rows = rows.unwrap_or(DEFAULT_ROWS as u64); let res: NuLazyFrame = lazy.to_polars().tail(rows).into(); res.to_pipeline_data(plugin, engine, call.head) } fn command_groupby( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, groupby: NuLazyGroupBy, ) -> Result<PipelineData, ShellError> { let rows: Option<usize> = call.opt(0)?; let rows = rows.unwrap_or(DEFAULT_ROWS); let res = groupby.to_polars().tail(Some(rows)); let res: NuLazyFrame = res.into(); res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&LastDF) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/drop_duplicates.rs
crates/nu_plugin_polars/src/dataframe/command/data/drop_duplicates.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::df; use polars::prelude::UniqueKeepStrategy; use crate::PolarsPlugin; use crate::values::CustomValueSupport; use crate::values::PolarsPluginType; use crate::values::NuDataFrame; use crate::values::utils::convert_columns_string; #[derive(Clone)] pub struct DropDuplicates; impl PluginCommand for DropDuplicates { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars drop-duplicates" } fn description(&self) -> &str { "Drops duplicate values in dataframe." } fn signature(&self) -> Signature { Signature::build(self.name()) .optional( "subset", SyntaxShape::Table(vec![]), "subset of columns to drop duplicates", ) .switch("maintain", "maintain order", Some('m')) .switch( "last", "keeps last duplicate value (by default keeps first)", Some('l'), ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "drop duplicates", example: "[[a b]; [1 2] [3 4] [1 2]] | polars into-df | polars drop-duplicates | polars sort-by a", result: Some( NuDataFrame::from( df!( "a" => &[1i64, 3], "b" => &[2i64, 4], ) .expect("should not fail"), ) .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let columns: Option<Vec<Value>> = call.opt(0)?; let (subset, col_span) = match columns { Some(cols) => { let (agg_string, col_span) = convert_columns_string(cols, call.head)?; (Some(agg_string), col_span) } None => (None, call.head), }; let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let subset_slice = subset.as_ref().map(|cols| &cols[..]); let keep_strategy = if call.has_flag("last")? { UniqueKeepStrategy::Last } else { UniqueKeepStrategy::First }; let polars_df = df .as_ref() .unique_stable(subset_slice, keep_strategy, None) .map_err(|e| ShellError::GenericError { error: "Error dropping duplicates".into(), msg: e.to_string(), span: Some(col_span), help: None, inner: vec![], })?; let df = NuDataFrame::new(df.from_lazy, polars_df); df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&DropDuplicates) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/replace.rs
crates/nu_plugin_polars/src/dataframe/command/data/replace.rs
use crate::{ PolarsPlugin, values::{CustomValueSupport, NuDataFrame, NuExpression, PolarsPluginType, str_to_dtype}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::{df, prelude::*}; #[derive(Clone)] pub struct Replace; impl PluginCommand for Replace { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars replace" } fn description(&self) -> &str { "Create an expression that replaces old values with new values" } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "old", SyntaxShape::OneOf(vec![SyntaxShape::Record(vec![]), SyntaxShape::List(Box::new(SyntaxShape::Any))]), "Values to be replaced", ) .optional( "new", SyntaxShape::List(Box::new(SyntaxShape::Any)), "Values to replace by", ) .switch( "strict", "Require that all values must be replaced or throw an error (ignored if `old` or `new` are expressions).", Some('s'), ) .named( "default", SyntaxShape::Any, "Set values that were not replaced to this value. If no default is specified, (default), an error is raised if any values were not replaced. Accepts expression input. Non-expression inputs are parsed as literals.", Some('d'), ) .named( "return-dtype", SyntaxShape::String, "Data type of the resulting expression. If set to `null` (default), the data type is determined automatically based on the other inputs.", Some('t'), ) .input_output_type( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ) .category(Category::Custom("expression".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Replace column with different values of same type", example: "[[a]; [1] [1] [2] [2]] | polars into-df | polars select (polars col a | polars replace [1 2] [10 20]) | polars collect", result: Some( NuDataFrame::from( df!("a" => [10, 10, 20, 20]) .expect("simple df for test should not fail"), ) .into_value(Span::test_data()), ), }, Example { description: "Replace column with different values of another type", example: "[[a]; [1] [1] [2] [2]] | polars into-df | polars select (polars col a | polars replace [1 2] [a b] --strict) | polars collect", result: Some( NuDataFrame::from( df!("a" => ["a", "a", "b", "b"]) .expect("simple df for test should not fail"), ) .into_value(Span::test_data()), ), }, Example { description: "Replace column with different values based on expressions (cannot be used with strict)", example: "[[a]; [1] [1] [2] [2]] | polars into-df | polars select (polars col a | polars replace [(polars col a | polars max)] [(polars col a | polars max | $in + 5)]) | polars collect", result: Some( NuDataFrame::from( df!("a" => [1, 1, 7, 7]) .expect("simple df for test should not fail"), ) .into_value(Span::test_data()), ), }, Example { description: "Replace column with different values based on expressions with default", example: "[[a]; [1] [1] [2] [3]] | polars into-df | polars select (polars col a | polars replace [1] [10] --default (polars col a | polars max | $in * 100) --strict) | polars collect", result: Some( NuDataFrame::from( df!("a" => [10, 10, 300, 300]) .expect("simple df for test should not fail"), ) .into_value(Span::test_data()), ), }, Example { description: "Replace column with different values based on expressions with default", example: "[[a]; [1] [1] [2] [3]] | polars into-df | polars select (polars col a | polars replace [1] [10] --default (polars col a | polars max | $in * 100) --strict --return-dtype str) | polars collect", result: Some( NuDataFrame::from( df!("a" => ["10", "10", "300", "300"]) .expect("simple df for test should not fail"), ) .into_value(Span::test_data()), ), }, Example { description: "Replace column with different values using a record", example: "[[a]; [1] [1] [2] [2]] | polars into-df | polars select (polars col a | polars replace {1: a, 2: b} --strict --return-dtype str) | polars collect", result: Some( NuDataFrame::from( df!("a" => ["a", "a", "b", "b"]) .expect("simple df for test should not fail"), ) .into_value(Span::test_data()), ), }, ] } fn search_terms(&self) -> Vec<&str> { vec!["replace"] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let (old_vals, new_vals) = match (call.req(0)?, call.opt::<Value>(1)?) { (Value::Record { val, .. }, None) => val .iter() .map(|(key, value)| (Value::string(key, call.head), value.clone())) .collect::<Vec<(Value, Value)>>() .into_iter() .unzip(), (Value::List { vals: old_vals, .. }, Some(Value::List { vals: new_vals, .. })) => { (old_vals, new_vals) } (_, _) => { return Err(LabeledError::from(ShellError::GenericError { error: "Invalid arguments".into(), msg: "".into(), span: Some(call.head), help: Some("`old` must be either a record or list. If `old` is a record, then `new` must not be specified. Otherwise, `new` must also be a list".into()), inner: vec![], })); } }; // let new_vals: Vec<Value> = call.req(1)?; let old = values_to_expr(plugin, call.head, old_vals)?; let new = values_to_expr(plugin, call.head, new_vals)?; let strict = call.has_flag("strict")?; let return_dtype = match call.get_flag::<String>("return-dtype")? { Some(dtype) => { if !strict { return Err(LabeledError::from(ShellError::GenericError { error: "`return-dtype` may only be used with `strict`".into(), msg: "".into(), span: Some(call.head), help: None, inner: vec![], })); } Some(str_to_dtype(&dtype, call.head)?) } None => None, }; let default = match call.get_flag::<Value>("default")? { Some(default) => { if !strict { return Err(LabeledError::from(ShellError::GenericError { error: "`default` may only be used with `strict`".into(), msg: "".into(), span: Some(call.head), help: None, inner: vec![], })); } Some(values_to_expr(plugin, call.head, vec![default])?) } None => None, }; let expr = NuExpression::try_from_pipeline(plugin, input, call.head)?; let expr: NuExpression = if strict { expr.into_polars() .replace_strict(old, new, default, return_dtype) .into() } else { expr.into_polars().replace(old, new).into() }; expr.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) } } fn values_to_expr( plugin: &PolarsPlugin, span: Span, values: Vec<Value>, ) -> Result<Expr, ShellError> { match values.first() { Some(Value::Int { .. }) => { let series_values = values .into_iter() .filter_map(|v| match v { Value::Int { val, .. } => Some(val), _ => None, }) .collect::<Vec<i64>>(); Ok(lit(Series::new("old".into(), &series_values))) } Some(Value::Bool { .. }) => { let series_values = values .into_iter() .filter_map(|v| match v { Value::Bool { val, .. } => Some(val), _ => None, }) .collect::<Vec<bool>>(); Ok(lit(Series::new("old".into(), &series_values))) } Some(Value::Float { .. }) => { let series_values = values .into_iter() .filter_map(|v| match v { Value::Float { val, .. } => Some(val), _ => None, }) .collect::<Vec<f64>>(); Ok(lit(Series::new("old".into(), &series_values))) } Some(Value::String { .. }) => { let series_values = values .into_iter() .filter_map(|v| match v { Value::String { val, .. } => Some(val), _ => None, }) .collect::<Vec<String>>(); Ok(lit(Series::new("old".into(), &series_values))) } Some(Value::Custom { .. }) => { if values.len() > 1 { return Err(ShellError::GenericError { error: "Multiple expressions to be replaced is not supported".into(), msg: "".into(), span: Some(span), help: None, inner: vec![], }); } NuExpression::try_from_value( plugin, values .first() .expect("Presence of first element is enforced at argument parsing."), ) .map(|expr| expr.into_polars()) } x @ Some(_) => Err(ShellError::GenericError { error: "Cannot convert input to expression".into(), msg: "".into(), span: Some(span), help: Some(format!("Unexpected type: {x:?}")), inner: vec![], }), None => Err(ShellError::GenericError { error: "Missing input values".into(), msg: "".into(), span: Some(span), help: None, inner: vec![], }), } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { test_polars_plugin_command(&Replace) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/unpivot.rs
crates/nu_plugin_polars/src/dataframe/command/data/unpivot.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Value, }; use polars::{ frame::explode::UnpivotArgsIR, prelude::{UnpivotArgsDSL, cols}, }; use polars_ops::pivot::UnpivotDF; use crate::{ PolarsPlugin, dataframe::values::utils::convert_columns_string, values::{CustomValueSupport, NuLazyFrame, PolarsPluginObject, PolarsPluginType}, }; use crate::values::{Column, NuDataFrame}; #[derive(Clone)] pub struct Unpivot; impl PluginCommand for Unpivot { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars unpivot" } fn description(&self) -> &str { "Unpivot a DataFrame from wide to long format." } fn signature(&self) -> Signature { Signature::build(self.name()) .required_named( "index", SyntaxShape::List(Box::new(SyntaxShape::Any)), "column names for unpivoting", Some('i'), ) .required_named( "on", SyntaxShape::List(Box::new(SyntaxShape::Any)), "column names used as value columns", Some('o'), ) .named( "variable-name", SyntaxShape::String, "optional name for variable column", Some('r'), ) .named( "value-name", SyntaxShape::String, "optional name for value column", Some('l'), ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "unpivot on an eager dataframe", example: "[[a b c d]; [x 1 4 a] [y 2 5 b] [z 3 6 c]] | polars into-df | polars unpivot -i [b c] -o [a d]", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "b".to_string(), vec![ Value::test_int(1), Value::test_int(2), Value::test_int(3), Value::test_int(1), Value::test_int(2), Value::test_int(3), ], ), Column::new( "c".to_string(), vec![ Value::test_int(4), Value::test_int(5), Value::test_int(6), Value::test_int(4), Value::test_int(5), Value::test_int(6), ], ), Column::new( "variable".to_string(), vec![ Value::test_string("a"), Value::test_string("a"), Value::test_string("a"), Value::test_string("d"), Value::test_string("d"), Value::test_string("d"), ], ), Column::new( "value".to_string(), vec![ Value::test_string("x"), Value::test_string("y"), Value::test_string("z"), Value::test_string("a"), Value::test_string("b"), Value::test_string("c"), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "unpivot on a lazy dataframe", example: "[[a b c d]; [x 1 4 a] [y 2 5 b] [z 3 6 c]] | polars into-lazy | polars unpivot -i [b c] -o [a d] | polars collect", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "b".to_string(), vec![ Value::test_int(1), Value::test_int(2), Value::test_int(3), Value::test_int(1), Value::test_int(2), Value::test_int(3), ], ), Column::new( "c".to_string(), vec![ Value::test_int(4), Value::test_int(5), Value::test_int(6), Value::test_int(4), Value::test_int(5), Value::test_int(6), ], ), Column::new( "variable".to_string(), vec![ Value::test_string("a"), Value::test_string("a"), Value::test_string("a"), Value::test_string("d"), Value::test_string("d"), Value::test_string("d"), ], ), Column::new( "value".to_string(), vec![ Value::test_string("x"), Value::test_string("y"), Value::test_string("z"), Value::test_string("a"), Value::test_string("b"), Value::test_string("c"), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); match PolarsPluginObject::try_from_pipeline(plugin, input, call.head)? { PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), _ => Err(ShellError::GenericError { error: "Must be a dataframe or lazy dataframe".into(), msg: "".into(), span: Some(call.head), help: None, inner: vec![], }), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let index_col: Vec<Value> = call.get_flag("index")?.expect("required value"); let on_col: Vec<Value> = call.get_flag("on")?.expect("required value"); let value_name: Option<Spanned<String>> = call.get_flag("value-name")?; let variable_name: Option<Spanned<String>> = call.get_flag("variable-name")?; let (index_col_string, index_col_span) = convert_columns_string(index_col, call.head)?; let (on_col_string, on_col_span) = convert_columns_string(on_col, call.head)?; check_column_datatypes(df.as_ref(), &index_col_string, index_col_span)?; check_column_datatypes(df.as_ref(), &on_col_string, on_col_span)?; let args = UnpivotArgsIR { on: on_col_string.iter().map(Into::into).collect(), index: index_col_string.iter().map(Into::into).collect(), variable_name: variable_name.map(|s| s.item.into()), value_name: value_name.map(|s| s.item.into()), }; let res = df .as_ref() .unpivot2(args) .map_err(|e| ShellError::GenericError { error: "Error calculating unpivot".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let res = NuDataFrame::new(false, res); res.to_pipeline_data(plugin, engine, call.head) } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuLazyFrame, ) -> Result<PipelineData, ShellError> { // todo - allow selectors to be used here let index_col: Vec<String> = call.get_flag("index")?.expect("required value"); // todo - allow selectors to be used here let on_col: Vec<String> = call.get_flag("on")?.expect("required value"); let value_name: Option<String> = call.get_flag("value-name")?; let variable_name: Option<String> = call.get_flag("variable-name")?; let unpivot_args = UnpivotArgsDSL { on: cols(on_col), index: cols(index_col), value_name: value_name.map(Into::into), variable_name: variable_name.map(Into::into), }; let polars_df = df.to_polars().unpivot(unpivot_args); let res = NuLazyFrame::new(false, polars_df); res.to_pipeline_data(plugin, engine, call.head) } fn check_column_datatypes<T: AsRef<str>>( df: &polars::prelude::DataFrame, cols: &[T], col_span: Span, ) -> Result<(), ShellError> { if cols.is_empty() { return Err(ShellError::GenericError { error: "Merge error".into(), msg: "empty column list".into(), span: Some(col_span), help: None, inner: vec![], }); } // Checking if they are same type if cols.len() > 1 { for w in cols.windows(2) { let l_series = df .column(w[0].as_ref()) .map_err(|e| ShellError::GenericError { error: "Error selecting columns".into(), msg: e.to_string(), span: Some(col_span), help: None, inner: vec![], })?; let r_series = df .column(w[1].as_ref()) .map_err(|e| ShellError::GenericError { error: "Error selecting columns".into(), msg: e.to_string(), span: Some(col_span), help: None, inner: vec![], })?; if l_series.dtype() != r_series.dtype() { return Err(ShellError::GenericError { error: "Merge error".into(), msg: "found different column types in list".into(), span: Some(col_span), help: Some(format!( "datatypes {} and {} are incompatible", l_series.dtype(), r_series.dtype() )), inner: vec![], }); } } } Ok(()) } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&Unpivot) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/fill_nan.rs
crates/nu_plugin_polars/src/dataframe/command/data/fill_nan.rs
use crate::{ PolarsPlugin, dataframe::values::{Column, NuDataFrame, NuExpression}, values::{CustomValueSupport, PolarsPluginObject, PolarsPluginType, cant_convert_err}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; #[derive(Clone)] pub struct LazyFillNA; impl PluginCommand for LazyFillNA { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars fill-nan" } fn description(&self) -> &str { "Replaces NaN values with the given expression." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "fill", SyntaxShape::Any, "Expression to use to fill the NAN values", ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Fills the NaN values with 0", example: "[1 2 NaN 3 NaN] | polars into-df | polars fill-nan 0", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_int(1), Value::test_int(2), Value::test_int(0), Value::test_int(3), Value::test_int(0), ], )], None, ) .expect("Df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Fills the NaN values of a whole dataframe", example: "[[a b]; [0.2 1] [0.1 NaN]] | polars into-df | polars fill-nan 0", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_float(0.2), Value::test_float(0.1)], ), Column::new( "b".to_string(), vec![Value::test_int(1), Value::test_int(0)], ), ], None, ) .expect("Df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let fill: Value = call.req(0)?; let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => { cmd_df(plugin, engine, call, df, fill, value.span()) } PolarsPluginObject::NuLazyFrame(lazy) => cmd_df( plugin, engine, call, lazy.collect(value.span())?, fill, value.span(), ), PolarsPluginObject::NuExpression(expr) => { Ok(cmd_expr(plugin, engine, call, expr, fill)?) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn cmd_df( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, frame: NuDataFrame, fill: Value, val_span: Span, ) -> Result<PipelineData, ShellError> { let columns = frame.columns(val_span)?; let dataframe = columns .into_iter() .map(|column| { let column_name = column.name().to_string(); let values = column .into_iter() .map(|value| { let span = value.span(); match value { Value::Float { val, .. } => { if val.is_nan() { fill.clone() } else { value } } Value::List { vals, .. } => { NuDataFrame::fill_list_nan(vals, span, fill.clone()) } _ => value, } }) .collect::<Vec<Value>>(); Column::new(column_name, values) }) .collect::<Vec<Column>>(); let df = NuDataFrame::try_from_columns(dataframe, None)?; df.to_pipeline_data(plugin, engine, call.head) } fn cmd_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, fill: Value, ) -> Result<PipelineData, ShellError> { let fill = NuExpression::try_from_value(plugin, &fill)?.into_polars(); let expr: NuExpression = expr.into_polars().fill_nan(fill).into(); expr.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&LazyFillNA) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/lit.rs
crates/nu_plugin_polars/src/dataframe/command/data/lit.rs
use crate::{ PolarsPlugin, dataframe::values::NuExpression, values::{CustomValueSupport, PolarsPluginType}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, Signature, SyntaxShape, Type, Value, record, }; #[derive(Clone)] pub struct ExprLit; impl PluginCommand for ExprLit { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars lit" } fn description(&self) -> &str { "Creates a literal expression." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "literal", SyntaxShape::Any, "literal to construct the expression", ) .input_output_type(Type::Any, PolarsPluginType::NuExpression.into()) .category(Category::Custom("expression".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Created a literal expression and converts it to a nu object", example: "polars lit 2 | polars into-nu", result: Some(Value::test_record(record! { "expr" => Value::test_string("literal"), "value" => Value::test_string("dyn int: 2"), })), }, Example { description: "Create a literal expression from date", example: "polars lit 2025-04-13 | polars into-nu", result: Some(Value::test_record(record! { "expr" => Value::test_record(record! { "expr" => Value::test_string("literal"), "value" => Value::test_string("dyn int: 1744502400000000000"), }), "dtype" => Value::test_string("Datetime('ns')"), "cast_options" => Value::test_string("STRICT") })), }, Example { description: "Create a literal expression from duration", example: "polars lit 3hr | polars into-nu", result: Some(Value::test_record(record! { "expr" => Value::test_record(record! { "expr" => Value::test_string("literal"), "value" => Value::test_string("dyn int: 10800000000000"), }), "dtype" => Value::test_string("Duration('ns')"), "cast_options" => Value::test_string("STRICT") })), }, ] } fn search_terms(&self) -> Vec<&str> { vec!["string", "literal", "expression"] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, _input: PipelineData, ) -> Result<PipelineData, LabeledError> { let literal: Value = call.req(0)?; let expr = NuExpression::try_from_value(plugin, &literal)?; expr.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { test_polars_plugin_command(&ExprLit) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/concat.rs
crates/nu_plugin_polars/src/dataframe/command/data/concat.rs
use crate::{ PolarsPlugin, values::{CustomValueSupport, NuLazyFrame, PolarsPluginType}, }; use crate::values::NuDataFrame; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value, }; use polars::{ df, prelude::{LazyFrame, UnionArgs}, }; #[derive(Clone)] pub struct ConcatDF; impl PluginCommand for ConcatDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars concat" } fn description(&self) -> &str { "Concatenate two or more dataframes." } fn signature(&self) -> Signature { Signature::build(self.name()) .switch("no-parallel", "Disable parallel execution", None) .switch("rechunk", "Rechunk the resulting dataframe", None) .switch("to-supertypes", "Cast to supertypes", None) .switch("diagonal", "Concatenate dataframes diagonally", None) .switch( "no-maintain-order", "Do not maintain order. The default behavior is to maintain order.", None, ) .switch( "from-partitioned-ds", "Concatenate dataframes from a partitioned dataset", None, ) .rest( "dataframes", SyntaxShape::Any, "The dataframes to concatenate", ) .input_output_types(vec![ (Type::Any, PolarsPluginType::NuDataFrame.into()), (Type::Any, PolarsPluginType::NuLazyFrame.into()), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Concatenates two dataframes with the dataframe in the pipeline.", example: "[[a b]; [1 2]] | polars into-df | polars concat ([[a b]; [3 4]] | polars into-df) ([[a b]; [5 6]] | polars into-df) | polars collect | polars sort-by [a b]", result: Some( NuDataFrame::from( df!( "a" => [1, 3, 5], "b" => [2, 4, 6], ) .expect("simple df for test should not fail"), ) .into_value(Span::test_data()), ), }, Example { description: "Concatenates three dataframes together", example: "polars concat ([[a b]; [1 2]] | polars into-df) ([[a b]; [3 4]] | polars into-df) ([[a b]; [5 6]] | polars into-df) | polars collect | polars sort-by [a b]", result: Some( NuDataFrame::from( df!( "a" => [1, 3, 5], "b" => [2, 4, 6], ) .expect("simple df for test should not fail"), ) .into_value(Span::test_data()), ), } ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let maybe_df = NuLazyFrame::try_from_pipeline_coerce(plugin, input, call.head).ok(); command_lazy(plugin, engine, call, maybe_df) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, maybe_lazy: Option<NuLazyFrame>, ) -> Result<PipelineData, ShellError> { let parallel = !call.has_flag("no-parallel")?; let rechunk = call.has_flag("rechunk")?; let to_supertypes = call.has_flag("to-supertypes")?; let diagonal = call.has_flag("diagonal")?; let from_partitioned_ds = call.has_flag("from-partitioned-ds")?; let maintain_order = !call.has_flag("no-maintain-order")?; let mut dataframes = call .rest::<Value>(0)? .iter() .map(|v| NuLazyFrame::try_from_value_coerce(plugin, v).map(|lazy| lazy.to_polars())) .collect::<Result<Vec<LazyFrame>, ShellError>>()?; if dataframes.is_empty() { Err(ShellError::GenericError { error: "At least one other dataframe must be provided".into(), msg: "".into(), span: Some(call.head), help: None, inner: vec![], }) } else { if let Some(lazy) = maybe_lazy.as_ref() { dataframes.insert(0, lazy.to_polars()); } let args = UnionArgs { parallel, rechunk, to_supertypes, diagonal, from_partitioned_ds, maintain_order, }; let res: NuLazyFrame = polars::prelude::concat(&dataframes, args) .map_err(|e| ShellError::GenericError { error: format!("Failed to concatenate dataframes: {e}"), msg: "".into(), span: Some(call.head), help: None, inner: vec![], })? .into(); res.to_pipeline_data(plugin, engine, call.head) } } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ConcatDF) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/fill_null.rs
crates/nu_plugin_polars/src/dataframe/command/data/fill_null.rs
use crate::{ PolarsPlugin, dataframe::values::{Column, NuDataFrame, NuExpression, NuLazyFrame}, values::{CustomValueSupport, PolarsPluginObject, PolarsPluginType, cant_convert_err}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; #[derive(Clone)] pub struct LazyFillNull; impl PluginCommand for LazyFillNull { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars fill-null" } fn description(&self) -> &str { "Replaces NULL values with the given expression." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "fill", SyntaxShape::Any, "Expression to use to fill the null values", ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Fills the null values by 0", example: "[1 2 2 3 3] | polars into-df | polars shift 2 | polars fill-null 0", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_int(0), Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_int(2), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Fills the null values in expression", example: "[[a]; [1] [2] [2] [3] [3]] | polars into-df | polars select (polars col a | polars shift 2 | polars fill-null 0) | polars collect", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "a".to_string(), vec![ Value::test_int(0), Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_int(2), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let fill: Value = call.req(0)?; let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => cmd_lazy(plugin, engine, call, df.lazy(), fill), PolarsPluginObject::NuLazyFrame(lazy) => cmd_lazy(plugin, engine, call, lazy, fill), PolarsPluginObject::NuExpression(expr) => cmd_expr(plugin, engine, call, expr, fill), _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn cmd_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, fill: Value, ) -> Result<PipelineData, ShellError> { let expr = NuExpression::try_from_value(plugin, &fill)?.into_polars(); let lazy = NuLazyFrame::new(lazy.from_eager, lazy.to_polars().fill_null(expr)); lazy.to_pipeline_data(plugin, engine, call.head) } fn cmd_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, fill: Value, ) -> Result<PipelineData, ShellError> { let fill = NuExpression::try_from_value(plugin, &fill)?.into_polars(); let expr: NuExpression = expr.into_polars().fill_null(fill).into(); expr.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&LazyFillNull) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/dummies.rs
crates/nu_plugin_polars/src/dataframe/command/data/dummies.rs
use crate::values::{NuDataFrame, PolarsPluginType}; use crate::{PolarsPlugin, values::CustomValueSupport}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, ShellError, Signature, Span}; use polars::{prelude::*, series::Series}; #[derive(Clone)] pub struct Dummies; impl PluginCommand for Dummies { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars dummies" } fn description(&self) -> &str { "Creates a new dataframe with dummy variables." } fn signature(&self) -> Signature { Signature::build(self.name()) .switch("drop-first", "Drop first row", Some('d')) .switch("drop-nulls", "Drop nulls", Some('n')) .switch("separator", "Optional separator", Some('s')) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Create new dataframe with dummy variables from a dataframe", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars dummies", result: Some( NuDataFrame::try_from_series_vec( vec![ Series::new("a_1".into(), &[1_u8, 0]), Series::new("a_3".into(), &[0_u8, 1]), Series::new("b_2".into(), &[1_u8, 0]), Series::new("b_4".into(), &[0_u8, 1]), ], Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Create new dataframe with dummy variables from a series", example: "[1 2 2 3 3] | polars into-df | polars dummies", result: Some( NuDataFrame::try_from_series_vec( vec![ Series::new("0_1".into(), &[1_u8, 0, 0, 0, 0]), Series::new("0_2".into(), &[0_u8, 1, 1, 0, 0]), Series::new("0_3".into(), &[0_u8, 0, 0, 1, 1]), ], Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { command(plugin, engine, call, input).map_err(LabeledError::from) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let drop_first: bool = call.has_flag("drop-first")?; let drop_nulls: bool = call.has_flag("drop-nulls")?; let separator: Option<String> = call.get_flag("separator")?; let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let polars_df = df .as_ref() .to_dummies(separator.as_deref(), drop_first, drop_nulls) .map_err(|e| ShellError::GenericError { error: "Error calculating dummies".into(), msg: e.to_string(), span: Some(call.head), help: Some("The only allowed column types for dummies are String or Int".into()), inner: vec![], })?; let df: NuDataFrame = polars_df.into(); df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&Dummies) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/shift.rs
crates/nu_plugin_polars/src/dataframe/command/data/shift.rs
use crate::{ PolarsPlugin, dataframe::values::{NuExpression, NuLazyFrame}, values::{CustomValueSupport, PolarsPluginObject, PolarsPluginType, cant_convert_err}, }; use crate::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars_plan::prelude::lit; #[derive(Clone)] pub struct Shift; impl PluginCommand for Shift { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars shift" } fn description(&self) -> &str { "Shifts the values by a given period." } fn signature(&self) -> Signature { Signature::build(self.name()) .required("period", SyntaxShape::Int, "shift period") .named( "fill", SyntaxShape::Any, "Expression used to fill the null values (lazy df)", Some('f'), ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe or lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Shifts the values by a given period", example: "[1 2 2 3 3] | polars into-df | polars shift 2 | polars drop-nulls", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![Value::test_int(1), Value::test_int(2), Value::test_int(2)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Shifts the values by a given period, fill absent values with 0", example: "[1 2 2 3 3] | polars into-lazy | polars shift 2 --fill 0 | polars collect", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_int(0), Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_int(2), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Shift values of a column, fill absent values with 0", example: "[[a]; [1] [2] [2] [3] [3]] | polars into-lazy | polars with-column {b: (polars col a | polars shift 2 --fill 0)} | polars collect", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![ Value::test_int(1), Value::test_int(2), Value::test_int(2), Value::test_int(3), Value::test_int(3), ], ), Column::new( "b".to_string(), vec![ Value::test_int(0), Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_int(2), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuExpression(expr) => { let shift: i64 = call.req(0)?; let fill: Option<Value> = call.get_flag("fill")?; let res: NuExpression = match fill { Some(ref fill) => { let fill_expr = NuExpression::try_from_value(plugin, fill)?.into_polars(); expr.into_polars() .shift_and_fill(lit(shift), fill_expr) .into() } None => expr.into_polars().shift(lit(shift)).into(), }; res.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyGroupBy, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let period: i64 = call.req(0)?; let series = df.as_series(call.head)?.shift(period); let df = NuDataFrame::try_from_series_vec(vec![series], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let shift: i64 = call.req(0)?; let fill: Option<Value> = call.get_flag("fill")?; let lazy = lazy.to_polars(); let lazy: NuLazyFrame = match fill { Some(ref fill) => { let expr = NuExpression::try_from_value(plugin, fill)?.into_polars(); lazy.shift_and_fill(lit(shift), expr).into() } None => lazy.shift(shift).into(), }; lazy.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&Shift) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/mod.rs
crates/nu_plugin_polars/src/dataframe/command/data/mod.rs
mod alias; mod append; mod arg_where; mod cast; mod col; mod collect; mod concat; mod cut; mod drop; mod drop_duplicates; mod drop_nulls; mod dummies; mod explode; mod fill_nan; mod fill_null; mod filter; mod filter_with; mod first; mod flatten; mod get; mod join; mod join_where; mod last; mod len; mod lit; mod pivot; mod qcut; mod query_df; mod rename; mod reverse; mod sample; mod select; mod slice; mod sort_by_expr; pub mod sql_context; pub mod sql_expr; mod struct_json_encode; mod take; mod unnest; mod unpivot; mod with_column; use filter::LazyFilter; mod replace; mod shift; mod unique; use crate::PolarsPlugin; use nu_plugin::PluginCommand; pub use alias::ExprAlias; pub use append::AppendDF; pub use arg_where::ExprArgWhere; pub use cast::CastDF; pub use col::ExprCol; pub use collect::LazyCollect; pub use drop::DropDF; pub use drop_duplicates::DropDuplicates; pub use drop_nulls::DropNulls; pub use dummies::Dummies; pub use explode::LazyExplode; use fill_nan::LazyFillNA; pub use fill_null::LazyFillNull; pub use first::FirstDF; use flatten::LazyFlatten; pub use get::GetDF; use join::LazyJoin; use join_where::LazyJoinWhere; pub use last::LastDF; pub use lit::ExprLit; use query_df::QueryDf; pub use rename::RenameDF; pub use replace::Replace; pub use sample::SampleDF; pub use shift::Shift; pub use slice::SliceDF; use sort_by_expr::LazySortBy; pub use take::TakeDF; pub use unique::Unique; pub use with_column::WithColumn; pub(crate) fn data_commands() -> Vec<Box<dyn PluginCommand<Plugin = PolarsPlugin>>> { vec![ Box::new(AppendDF), Box::new(CastDF), Box::new(cut::CutSeries), Box::new(DropDF), Box::new(concat::ConcatDF), Box::new(DropDuplicates), Box::new(DropNulls), Box::new(Dummies), Box::new(filter_with::FilterWith), Box::new(GetDF), Box::new(pivot::PivotDF), Box::new(unpivot::Unpivot), Box::new(FirstDF), Box::new(LastDF), Box::new(len::ExprLen), Box::new(RenameDF), Box::new(SampleDF), Box::new(SliceDF), Box::new(TakeDF), Box::new(QueryDf), Box::new(WithColumn), Box::new(ExprAlias), Box::new(ExprArgWhere), Box::new(ExprLit), Box::new(ExprCol), Box::new(LazyCollect), Box::new(LazyExplode), Box::new(LazyFillNA), Box::new(LazyFillNull), Box::new(LazyFlatten), Box::new(LazyJoin), Box::new(LazyJoinWhere), Box::new(reverse::LazyReverse), Box::new(select::LazySelect), Box::new(LazySortBy), Box::new(LazyFilter), Box::new(Replace), Box::new(Shift), Box::new(struct_json_encode::StructJsonEncode), Box::new(qcut::QCutSeries), Box::new(Unique), Box::new(unnest::UnnestDF), ] }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/drop.rs
crates/nu_plugin_polars/src/dataframe/command/data/drop.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use crate::PolarsPlugin; use crate::values::{CustomValueSupport, PolarsPluginType}; use crate::values::utils::convert_columns; use crate::values::{Column, NuDataFrame}; #[derive(Clone)] pub struct DropDF; impl PluginCommand for DropDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars drop" } fn description(&self) -> &str { "Creates a new dataframe by dropping the selected columns." } fn signature(&self) -> Signature { Signature::build(self.name()) .rest("rest", SyntaxShape::Any, "column names to be dropped") .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "drop column a", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars drop a", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(4)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let columns: Vec<Value> = call.rest(0)?; let (col_string, col_span) = convert_columns(columns, call.head)?; let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let new_df = col_string .first() .ok_or_else(|| ShellError::GenericError { error: "Empty names list".into(), msg: "No column names were found".into(), span: Some(col_span), help: None, inner: vec![], }) .and_then(|col| { df.as_ref() .drop(&col.item) .map_err(|e| ShellError::GenericError { error: "Error dropping column".into(), msg: e.to_string(), span: Some(col.span), help: None, inner: vec![], }) })?; // If there are more columns in the drop selection list, these // are added from the resulting dataframe let polars_df = col_string.iter().skip(1).try_fold(new_df, |new_df, col| { new_df .drop(&col.item) .map_err(|e| ShellError::GenericError { error: "Error dropping column".into(), msg: e.to_string(), span: Some(col.span), help: None, inner: vec![], }) })?; let final_df = NuDataFrame::new(df.from_lazy, polars_df); final_df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&DropDF) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/append.rs
crates/nu_plugin_polars/src/dataframe/command/data/append.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use crate::{ PolarsPlugin, values::{Axis, Column, CustomValueSupport, NuDataFrame, PolarsPluginType}, }; #[derive(Clone)] pub struct AppendDF; impl PluginCommand for AppendDF { type Plugin = PolarsPlugin; fn signature(&self) -> Signature { Signature::build(self.name()) .required("other", SyntaxShape::Any, "other dataframe to append") .switch("col", "append as new columns instead of rows", Some('c')) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { command(plugin, engine, call, input).map_err(LabeledError::from) } fn name(&self) -> &str { "polars append" } fn description(&self) -> &str { "Appends a new dataframe." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Appends a dataframe as new columns", example: r#"let a = ([[a b]; [1 2] [3 4]] | polars into-df); $a | polars append $a"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(3)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(4)], ), Column::new( "a_x".to_string(), vec![Value::test_int(1), Value::test_int(3)], ), Column::new( "b_x".to_string(), vec![Value::test_int(2), Value::test_int(4)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Appends a dataframe merging at the end of columns", example: r#"let a = ([[a b]; [1 2] [3 4]] | polars into-df); $a | polars append $a --col"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![ Value::test_int(1), Value::test_int(3), Value::test_int(1), Value::test_int(3), ], ), Column::new( "b".to_string(), vec![ Value::test_int(2), Value::test_int(4), Value::test_int(2), Value::test_int(4), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let other: Value = call.req(0)?; let axis = if call.has_flag("col")? { Axis::Column } else { Axis::Row }; let df_other = NuDataFrame::try_from_value_coerce(plugin, &other, call.head)?; let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let df = df.append_df(&df_other, axis, call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&AppendDF) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false