-
Notifications
You must be signed in to change notification settings - Fork 1.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add a describe method on DataFrame like Polars #5226
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -20,19 +20,22 @@ | |
use std::any::Any; | ||
use std::sync::Arc; | ||
|
||
use arrow::array::Int64Array; | ||
use arrow::array::{ArrayRef, Int64Array, StringArray}; | ||
use arrow::compute::{cast, concat}; | ||
use arrow::datatypes::{DataType, Field}; | ||
use async_trait::async_trait; | ||
use datafusion_common::DataFusionError; | ||
use parquet::file::properties::WriterProperties; | ||
|
||
use datafusion_common::from_slice::FromSlice; | ||
use datafusion_common::{Column, DFSchema, ScalarValue}; | ||
use datafusion_expr::TableProviderFilterPushDown; | ||
use datafusion_expr::{TableProviderFilterPushDown, UNNAMED_TABLE}; | ||
|
||
use crate::arrow::datatypes::Schema; | ||
use crate::arrow::datatypes::SchemaRef; | ||
use crate::arrow::record_batch::RecordBatch; | ||
use crate::arrow::util::pretty; | ||
use crate::datasource::{MemTable, TableProvider}; | ||
use crate::datasource::{provider_as_source, MemTable, TableProvider}; | ||
use crate::error::Result; | ||
use crate::execution::{ | ||
context::{SessionState, TaskContext}, | ||
|
@@ -302,6 +305,155 @@ impl DataFrame { | |
)) | ||
} | ||
|
||
/// Summary statistics for a DataFrame. Only summarizes numeric datatypes at the moment and | ||
/// returns nulls for non numeric datatypes. Try in keep output similar to pandas | ||
/// | ||
/// ``` | ||
/// # use datafusion::prelude::*; | ||
/// # use datafusion::error::Result; | ||
/// # use arrow::util::pretty; | ||
/// # #[tokio::main] | ||
/// # async fn main() -> Result<()> { | ||
/// let ctx = SessionContext::new(); | ||
/// let df = ctx.read_csv("tests/tpch-csv/customer.csv", CsvReadOptions::new()).await?; | ||
/// df.describe().await.unwrap(); | ||
/// | ||
/// # Ok(()) | ||
/// # } | ||
/// ``` | ||
pub async fn describe(self) -> Result<Self> { | ||
//the functions now supported | ||
let supported_describe_functions = vec!["count", "null_count", "max", "min"]; | ||
|
||
let fields_iter = self.schema().fields().iter(); | ||
|
||
//define describe column | ||
let mut describe_schemas = fields_iter | ||
.clone() | ||
.map(|field| { | ||
if field.data_type().is_numeric() { | ||
Field::new(field.name(), DataType::Float64, true) | ||
} else { | ||
Field::new(field.name(), DataType::Utf8, true) | ||
} | ||
}) | ||
.collect::<Vec<_>>(); | ||
describe_schemas.insert(0, Field::new("describe", DataType::Utf8, false)); | ||
|
||
//collect recordBatch | ||
let describe_record_batch = vec![ | ||
// count aggregation | ||
self.clone() | ||
.aggregate( | ||
vec![], | ||
fields_iter | ||
.clone() | ||
.map(|f| datafusion_expr::count(col(f.name())).alias(f.name())) | ||
.collect::<Vec<_>>(), | ||
)? | ||
.collect() | ||
.await?, | ||
// null_count aggregation | ||
self.clone() | ||
.aggregate( | ||
vec![], | ||
fields_iter | ||
.clone() | ||
.map(|f| { | ||
datafusion_expr::count(datafusion_expr::is_null( | ||
col(f.name()), | ||
)) | ||
.alias(f.name()) | ||
}) | ||
.collect::<Vec<_>>(), | ||
)? | ||
.collect() | ||
.await?, | ||
// max aggregation | ||
self.clone() | ||
.aggregate( | ||
vec![], | ||
fields_iter | ||
.clone() | ||
.filter(|f| { | ||
!matches!(f.data_type(), DataType::Binary | DataType::Boolean) | ||
}) | ||
.map(|f| datafusion_expr::max(col(f.name())).alias(f.name())) | ||
.collect::<Vec<_>>(), | ||
)? | ||
.collect() | ||
.await?, | ||
// min aggregation | ||
self.clone() | ||
.aggregate( | ||
vec![], | ||
fields_iter | ||
.clone() | ||
.filter(|f| { | ||
!matches!(f.data_type(), DataType::Binary | DataType::Boolean) | ||
}) | ||
.map(|f| datafusion_expr::min(col(f.name())).alias(f.name())) | ||
.collect::<Vec<_>>(), | ||
)? | ||
.collect() | ||
.await?, | ||
]; | ||
|
||
let mut array_ref_vec: Vec<ArrayRef> = vec![]; | ||
for field in fields_iter { | ||
let mut array_datas = vec![]; | ||
for record_batch in describe_record_batch.iter() { | ||
let column = record_batch.get(0).unwrap().column_by_name(field.name()); | ||
match column { | ||
Some(c) => { | ||
if field.data_type().is_numeric() { | ||
array_datas.push(cast(c, &DataType::Float64)?); | ||
} else { | ||
array_datas.push(cast(c, &DataType::Utf8)?); | ||
} | ||
} | ||
//if None mean the column cannot be min/max aggregation | ||
None => { | ||
array_datas.push(Arc::new(StringArray::from_slice(["null"]))); | ||
} | ||
} | ||
} | ||
|
||
array_ref_vec.push(concat( | ||
array_datas | ||
.iter() | ||
.map(|af| af.as_ref()) | ||
.collect::<Vec<_>>() | ||
.as_slice(), | ||
)?); | ||
} | ||
|
||
//insert first column with function names | ||
array_ref_vec.insert( | ||
0, | ||
Arc::new(StringArray::from_slice( | ||
supported_describe_functions.clone(), | ||
)), | ||
); | ||
|
||
let describe_record_batch = | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 |
||
RecordBatch::try_new(Arc::new(Schema::new(describe_schemas)), array_ref_vec)?; | ||
|
||
let provider = MemTable::try_new( | ||
describe_record_batch.schema(), | ||
vec![vec![describe_record_batch]], | ||
)?; | ||
Ok(DataFrame::new( | ||
self.session_state, | ||
LogicalPlanBuilder::scan( | ||
UNNAMED_TABLE, | ||
provider_as_source(Arc::new(provider)), | ||
None, | ||
)? | ||
.build()?, | ||
)) | ||
} | ||
|
||
/// Sort the DataFrame by the specified sorting expressions. Any expression can be turned into | ||
/// a sort expression by calling its [sort](../logical_plan/enum.Expr.html#method.sort) method. | ||
/// | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would expect that the schema for
count
andnull_count
were alwaysInt64
and the schema for min/max were alwaysUtf8
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the describe method return schema like this.

the each column should have same datatype .
for example :
bool_col
oncount/null_count
return Int64 ; error onmin/max
, so makebool_col
datatypeUTF8
;float_col
oncount/null_count
return Int64 ; onmin/max
return float, so makefloat_col
datatypeFloat64