forked from extern/nushell
# Description There are times where explicitly specifying a schema for a dataframe is needed such as: - Opening CSV and JSON lines files and needing provide more information to polars to keep it from failing or in a desire to override default type conversion - When converting a nushell value to a dataframe and wanting to override the default conversion behaviors. This pull requests provides: - A flag to allow specifying a schema when using dfr into-df - A flag to allow specifying a schema when using dfr open that works for CSV and JSON types - A new command `dfr schema` which displays schema information and will allow display support schema dtypes Schema is specified creating a record that has the key value and the dtype. Examples usages: ``` {a:1, b:{a:2}} | dfr into-df -s {a: u8, b: {a: i32}} | dfr schema {a: 1, b: {a: [1 2 3]}, c: [a b c]} | dfr into-df -s {a: u8, b: {a: list<u64>}, c: list<str>} | dfr schema dfr open -s {pid: i32, ppid: i32, name: str, status: str, cpu: f64, mem: i64, virtual: i64} /tmp/ps.jsonl | dfr schema ``` Supported dtypes: null bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 str binary date datetime[time_unit: (ms, us, ns) timezone (optional)] duration[time_unit: (ms, us, ns)] time object unknown list[dtype] structs are also supported but are specified via another record: {a: u8, b: {d: str}} Another feature with the dfr schema command is that it returns the data back in a format that can be passed to provide a valid schema that can be passed in as schema argument: <img width="638" alt="Screenshot 2024-01-29 at 10 23 58" src="https://github.com/nushell/nushell/assets/56345/b49c3bff-5cda-4c86-975a-dfd91d991373"> --------- Co-authored-by: Jack Wright <jack.wright@disqo.com>
159 lines
5.4 KiB
Rust
159 lines
5.4 KiB
Rust
use crate::dataframe::values::{Column, NuDataFrame, NuExpression, NuLazyFrame};
|
|
|
|
use nu_protocol::{
|
|
ast::Call,
|
|
engine::{Command, EngineState, Stack},
|
|
Category, Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value,
|
|
};
|
|
|
|
#[derive(Clone)]
|
|
pub struct LazyExplode;
|
|
|
|
impl Command for LazyExplode {
|
|
fn name(&self) -> &str {
|
|
"dfr explode"
|
|
}
|
|
|
|
fn usage(&self) -> &str {
|
|
"Explodes a dataframe or creates a explode expression."
|
|
}
|
|
|
|
fn signature(&self) -> Signature {
|
|
Signature::build(self.name())
|
|
.rest(
|
|
"columns",
|
|
SyntaxShape::String,
|
|
"columns to explode, only applicable for dataframes",
|
|
)
|
|
.input_output_types(vec![
|
|
(
|
|
Type::Custom("expression".into()),
|
|
Type::Custom("expression".into()),
|
|
),
|
|
(
|
|
Type::Custom("dataframe".into()),
|
|
Type::Custom("dataframe".into()),
|
|
),
|
|
])
|
|
.category(Category::Custom("lazyframe".into()))
|
|
}
|
|
|
|
fn examples(&self) -> Vec<Example> {
|
|
vec![
|
|
Example {
|
|
description: "Explode the specified dataframe",
|
|
example: "[[id name hobbies]; [1 Mercy [Cycling Knitting]] [2 Bob [Skiing Football]]] | dfr into-df | dfr explode hobbies | dfr 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 explode the values",
|
|
example: "[[id name hobbies]; [1 Mercy [Cycling Knitting]] [2 Bob [Skiing Football]]] | dfr into-df | dfr select (dfr col hobbies | dfr explode)",
|
|
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,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
call: &Call,
|
|
input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
explode(call, input)
|
|
}
|
|
}
|
|
|
|
pub(crate) fn explode(call: &Call, input: PipelineData) -> Result<PipelineData, ShellError> {
|
|
let value = input.into_value(call.head);
|
|
if NuDataFrame::can_downcast(&value) {
|
|
let df = NuLazyFrame::try_from_value(value)?;
|
|
let columns: Vec<String> = call
|
|
.positional_iter()
|
|
.filter_map(|e| e.as_string())
|
|
.collect();
|
|
|
|
let exploded = df
|
|
.into_polars()
|
|
.explode(columns.iter().map(AsRef::as_ref).collect::<Vec<&str>>());
|
|
|
|
Ok(PipelineData::Value(
|
|
NuLazyFrame::from(exploded).into_value(call.head)?,
|
|
None,
|
|
))
|
|
} else {
|
|
let expr = NuExpression::try_from_value(value)?;
|
|
let expr: NuExpression = expr.into_polars().explode().into();
|
|
|
|
Ok(PipelineData::Value(
|
|
NuExpression::into_value(expr, call.head),
|
|
None,
|
|
))
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod test {
|
|
use super::super::super::test_dataframe::{build_test_engine_state, test_dataframe_example};
|
|
use super::*;
|
|
use crate::dataframe::lazy::aggregate::LazyAggregate;
|
|
use crate::dataframe::lazy::groupby::ToLazyGroupBy;
|
|
|
|
#[test]
|
|
fn test_examples_dataframe() {
|
|
let mut engine_state = build_test_engine_state(vec![Box::new(LazyExplode {})]);
|
|
test_dataframe_example(&mut engine_state, &LazyExplode.examples()[0]);
|
|
}
|
|
|
|
#[ignore]
|
|
#[test]
|
|
fn test_examples_expression() {
|
|
let mut engine_state = build_test_engine_state(vec![
|
|
Box::new(LazyExplode {}),
|
|
Box::new(LazyAggregate {}),
|
|
Box::new(ToLazyGroupBy {}),
|
|
]);
|
|
test_dataframe_example(&mut engine_state, &LazyExplode.examples()[1]);
|
|
}
|
|
}
|