-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
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
fix: Make output dtype known for list.to_struct
when fields
are passed
#19439
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
3b9b86b
c
nameexhaustion 3f6f409
c
nameexhaustion 864ec84
c
nameexhaustion 6a5a015
c
nameexhaustion 8482ee4
ensure schema is `Unknown` if output names not given
nameexhaustion 836f0d4
c
nameexhaustion fd442be
c
nameexhaustion 76bad1e
c
nameexhaustion 9d7e565
c
nameexhaustion 372a8b4
c
nameexhaustion c9197aa
undo warnings
nameexhaustion eed6f03
c
nameexhaustion 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 |
---|---|---|
|
@@ -5,82 +5,220 @@ use polars_utils::pl_str::PlSmallStr; | |
|
||
use super::*; | ||
|
||
#[derive(Copy, Clone, Debug)] | ||
#[derive(Clone, Eq, PartialEq, Hash, Debug)] | ||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] | ||
pub enum ListToStructArgs { | ||
FixedWidth(Arc<[PlSmallStr]>), | ||
InferWidth { | ||
infer_field_strategy: ListToStructWidthStrategy, | ||
get_index_name: Option<NameGenerator>, | ||
/// If this is 0, it means unbounded. | ||
max_fields: usize, | ||
}, | ||
} | ||
|
||
#[derive(Clone, Eq, PartialEq, Hash, Debug)] | ||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] | ||
pub enum ListToStructWidthStrategy { | ||
FirstNonNull, | ||
MaxWidth, | ||
} | ||
|
||
fn det_n_fields(ca: &ListChunked, n_fields: ListToStructWidthStrategy) -> usize { | ||
match n_fields { | ||
ListToStructWidthStrategy::MaxWidth => { | ||
let mut max = 0; | ||
|
||
ca.downcast_iter().for_each(|arr| { | ||
let offsets = arr.offsets().as_slice(); | ||
let mut last = offsets[0]; | ||
for o in &offsets[1..] { | ||
let len = (*o - last) as usize; | ||
max = std::cmp::max(max, len); | ||
last = *o; | ||
impl ListToStructArgs { | ||
pub fn get_output_dtype(&self, input_dtype: &DataType) -> PolarsResult<DataType> { | ||
let DataType::List(inner_dtype) = input_dtype else { | ||
polars_bail!( | ||
InvalidOperation: | ||
"attempted list to_struct on non-list dtype: {}", | ||
input_dtype | ||
); | ||
}; | ||
let inner_dtype = inner_dtype.as_ref(); | ||
|
||
match self { | ||
Self::FixedWidth(names) => Ok(DataType::Struct( | ||
names | ||
.iter() | ||
.map(|x| Field::new(x.clone(), inner_dtype.clone())) | ||
.collect::<Vec<_>>(), | ||
)), | ||
Self::InferWidth { | ||
get_index_name, | ||
max_fields, | ||
.. | ||
} if *max_fields > 0 => { | ||
let get_index_name_func = get_index_name.as_ref().map_or( | ||
&_default_struct_name_gen as &dyn Fn(usize) -> PlSmallStr, | ||
|x| x.0.as_ref(), | ||
); | ||
Ok(DataType::Struct( | ||
(0..*max_fields) | ||
.map(|i| Field::new(get_index_name_func(i), inner_dtype.clone())) | ||
.collect::<Vec<_>>(), | ||
)) | ||
}, | ||
Self::InferWidth { .. } => Ok(DataType::Unknown(UnknownKind::Any)), | ||
} | ||
} | ||
|
||
fn det_n_fields(&self, ca: &ListChunked) -> usize { | ||
match self { | ||
Self::FixedWidth(v) => v.len(), | ||
Self::InferWidth { | ||
infer_field_strategy, | ||
max_fields, | ||
.. | ||
} => { | ||
let inferred = match infer_field_strategy { | ||
ListToStructWidthStrategy::MaxWidth => { | ||
let mut max = 0; | ||
|
||
ca.downcast_iter().for_each(|arr| { | ||
let offsets = arr.offsets().as_slice(); | ||
let mut last = offsets[0]; | ||
for o in &offsets[1..] { | ||
let len = (*o - last) as usize; | ||
max = std::cmp::max(max, len); | ||
last = *o; | ||
} | ||
}); | ||
max | ||
}, | ||
ListToStructWidthStrategy::FirstNonNull => { | ||
let mut len = 0; | ||
for arr in ca.downcast_iter() { | ||
let offsets = arr.offsets().as_slice(); | ||
let mut last = offsets[0]; | ||
for o in &offsets[1..] { | ||
len = (*o - last) as usize; | ||
if len > 0 { | ||
break; | ||
} | ||
last = *o; | ||
} | ||
if len > 0 { | ||
break; | ||
} | ||
} | ||
len | ||
}, | ||
}; | ||
|
||
if *max_fields > 0 { | ||
inferred.min(*max_fields) | ||
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.
|
||
} else { | ||
inferred | ||
} | ||
}); | ||
max | ||
}, | ||
ListToStructWidthStrategy::FirstNonNull => { | ||
let mut len = 0; | ||
for arr in ca.downcast_iter() { | ||
let offsets = arr.offsets().as_slice(); | ||
let mut last = offsets[0]; | ||
for o in &offsets[1..] { | ||
len = (*o - last) as usize; | ||
if len > 0 { | ||
break; | ||
} | ||
last = *o; | ||
}, | ||
} | ||
} | ||
|
||
fn set_output_names(&self, columns: &mut [Series]) { | ||
match self { | ||
Self::FixedWidth(v) => { | ||
assert_eq!(columns.len(), v.len()); | ||
|
||
for (c, name) in columns.iter_mut().zip(v.iter()) { | ||
c.rename(name.clone()); | ||
} | ||
if len > 0 { | ||
break; | ||
}, | ||
Self::InferWidth { get_index_name, .. } => { | ||
let get_index_name_func = get_index_name.as_ref().map_or( | ||
&_default_struct_name_gen as &dyn Fn(usize) -> PlSmallStr, | ||
|x| x.0.as_ref(), | ||
); | ||
|
||
for (i, c) in columns.iter_mut().enumerate() { | ||
c.rename(get_index_name_func(i)); | ||
} | ||
} | ||
len | ||
}, | ||
}, | ||
} | ||
} | ||
} | ||
|
||
#[derive(Clone)] | ||
pub struct NameGenerator(pub Arc<dyn Fn(usize) -> PlSmallStr + Send + Sync>); | ||
|
||
impl NameGenerator { | ||
pub fn from_func(func: impl Fn(usize) -> PlSmallStr + Send + Sync + 'static) -> Self { | ||
Self(Arc::new(func)) | ||
} | ||
} | ||
|
||
impl std::fmt::Debug for NameGenerator { | ||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
write!( | ||
f, | ||
"list::to_struct::NameGenerator function at 0x{:016x}", | ||
self.0.as_ref() as *const _ as *const () as usize | ||
) | ||
} | ||
} | ||
|
||
impl Eq for NameGenerator {} | ||
|
||
impl PartialEq for NameGenerator { | ||
fn eq(&self, other: &Self) -> bool { | ||
Arc::ptr_eq(&self.0, &other.0) | ||
} | ||
} | ||
|
||
pub type NameGenerator = Arc<dyn Fn(usize) -> PlSmallStr + Send + Sync>; | ||
impl std::hash::Hash for NameGenerator { | ||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) { | ||
state.write_usize(Arc::as_ptr(&self.0) as *const () as usize) | ||
} | ||
} | ||
|
||
pub fn _default_struct_name_gen(idx: usize) -> PlSmallStr { | ||
format_pl_smallstr!("field_{idx}") | ||
} | ||
|
||
pub trait ToStruct: AsList { | ||
fn to_struct( | ||
&self, | ||
n_fields: ListToStructWidthStrategy, | ||
name_generator: Option<NameGenerator>, | ||
) -> PolarsResult<StructChunked> { | ||
fn to_struct(&self, args: &ListToStructArgs) -> PolarsResult<StructChunked> { | ||
let ca = self.as_list(); | ||
let n_fields = det_n_fields(ca, n_fields); | ||
let n_fields = args.det_n_fields(ca); | ||
|
||
let name_generator = name_generator | ||
.as_deref() | ||
.unwrap_or(&_default_struct_name_gen); | ||
|
||
let fields = POOL.install(|| { | ||
let mut fields = POOL.install(|| { | ||
(0..n_fields) | ||
.into_par_iter() | ||
.map(|i| { | ||
ca.lst_get(i as i64, true).map(|mut s| { | ||
s.rename(name_generator(i)); | ||
s | ||
}) | ||
}) | ||
.map(|i| ca.lst_get(i as i64, true)) | ||
.collect::<PolarsResult<Vec<_>>>() | ||
})?; | ||
|
||
args.set_output_names(&mut fields); | ||
|
||
StructChunked::from_series(ca.name().clone(), ca.len(), fields.iter()) | ||
} | ||
} | ||
|
||
impl ToStruct for ListChunked {} | ||
|
||
#[cfg(feature = "serde")] | ||
mod _serde_impl { | ||
use super::*; | ||
|
||
impl serde::Serialize for NameGenerator { | ||
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error> | ||
where | ||
S: serde::Serializer, | ||
{ | ||
use serde::ser::Error; | ||
Err(S::Error::custom( | ||
"cannot serialize name generator function for to_struct, \ | ||
consider passing a list of field names instead.", | ||
)) | ||
} | ||
} | ||
|
||
impl<'de> serde::Deserialize<'de> for NameGenerator { | ||
fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error> | ||
where | ||
D: serde::Deserializer<'de>, | ||
{ | ||
use serde::de::Error; | ||
Err(D::Error::custom( | ||
"invalid data: attempted to deserialize list::to_struct::NameGenerator", | ||
)) | ||
} | ||
} | ||
} |
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
Oops, something went wrong.
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.
drive-by - outdated todo