Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/crates/polars-expr/src/expressions/gather.rs
8424 views
1
use polars_core::chunked_array::cast::CastOptions;
2
use polars_core::prelude::arity::unary_elementwise_values;
3
use polars_core::prelude::*;
4
use polars_ops::prelude::lst_get;
5
use polars_ops::series::convert_and_bound_index;
6
use polars_utils::index::ToIdx;
7
8
use super::*;
9
use crate::expressions::{AggState, AggregationContext, PhysicalExpr, UpdateGroups};
10
11
pub struct GatherExpr {
12
pub(crate) phys_expr: Arc<dyn PhysicalExpr>,
13
pub(crate) idx: Arc<dyn PhysicalExpr>,
14
pub(crate) expr: Expr,
15
pub(crate) returns_scalar: bool,
16
pub(crate) null_on_oob: bool,
17
}
18
19
impl PhysicalExpr for GatherExpr {
20
fn as_expression(&self) -> Option<&Expr> {
21
Some(&self.expr)
22
}
23
24
fn evaluate(&self, df: &DataFrame, state: &ExecutionState) -> PolarsResult<Column> {
25
let series = self.phys_expr.evaluate(df, state)?;
26
let idx = self.idx.evaluate(df, state)?;
27
let idx =
28
convert_and_bound_index(idx.as_materialized_series(), series.len(), self.null_on_oob)?;
29
series.take(&idx)
30
}
31
32
#[allow(clippy::ptr_arg)]
33
fn evaluate_on_groups<'a>(
34
&self,
35
df: &DataFrame,
36
groups: &'a GroupPositions,
37
state: &ExecutionState,
38
) -> PolarsResult<AggregationContext<'a>> {
39
let mut ac = self.phys_expr.evaluate_on_groups(df, groups, state)?;
40
let mut idx = self.idx.evaluate_on_groups(df, groups, state)?;
41
42
let ac_list = ac.aggregated_as_list();
43
44
if self.returns_scalar {
45
polars_ensure!(
46
!matches!(idx.agg_state(), AggState::AggregatedList(_) | AggState::NotAggregated(_)),
47
ComputeError: "expected single index"
48
);
49
50
// For returns_scalar=true, we can dispatch to `list.get`.
51
let idx = idx.flat_naive();
52
let idx = idx.cast(&DataType::Int64)?;
53
let idx = idx.i64().unwrap();
54
let taken = lst_get(ac_list.as_ref(), idx, true)?;
55
56
ac.with_values_and_args(taken, true, Some(&self.expr), false, true)?;
57
ac.with_update_groups(UpdateGroups::No);
58
return Ok(ac);
59
}
60
61
// Cast the indices to
62
// - IdxSize, if the idx only contains positive integers.
63
// - Int64, if the idx contains negative numbers.
64
// This may give false positives if there are masked out elements.
65
let idx = idx.aggregated_as_list();
66
let idx = idx.apply_to_inner(&|s| match s.dtype() {
67
dtype if dtype == &IDX_DTYPE => Ok(s),
68
dtype if dtype.is_unsigned_integer() => {
69
s.cast_with_options(&IDX_DTYPE, CastOptions::Strict)
70
},
71
72
dtype if dtype.is_signed_integer() => {
73
let has_negative_integers = s.lt(0)?.any();
74
if has_negative_integers && dtype == &DataType::Int64 {
75
Ok(s)
76
} else if has_negative_integers {
77
s.cast_with_options(&DataType::Int64, CastOptions::Strict)
78
} else {
79
s.cast_with_options(&IDX_DTYPE, CastOptions::Overflowing)
80
}
81
},
82
_ => polars_bail!(
83
op = "gather/get",
84
got = s.dtype(),
85
expected = "integer type"
86
),
87
})?;
88
89
let taken = if idx.inner_dtype() == &IDX_DTYPE {
90
// Fast path: all indices are positive.
91
92
ac_list
93
.amortized_iter()
94
.zip(idx.amortized_iter())
95
.map(|(s, idx)| Some(s?.as_ref().take(idx?.as_ref().idx().unwrap())))
96
.map(|opt_res| opt_res.transpose())
97
.collect::<PolarsResult<ListChunked>>()?
98
.with_name(ac.get_values().name().clone())
99
} else {
100
// Slower path: some indices may be negative.
101
assert!(idx.inner_dtype() == &DataType::Int64);
102
103
ac_list
104
.amortized_iter()
105
.zip(idx.amortized_iter())
106
.map(|(s, idx)| {
107
let s = s?;
108
let idx = idx?;
109
let idx = idx.as_ref().i64().unwrap();
110
let target_len = s.as_ref().len() as u64;
111
let idx = unary_elementwise_values(idx, |v| v.to_idx(target_len));
112
Some(s.as_ref().take(&idx))
113
})
114
.map(|opt_res| opt_res.transpose())
115
.collect::<PolarsResult<ListChunked>>()?
116
.with_name(ac.get_values().name().clone())
117
};
118
119
ac.with_agg_state(AggState::AggregatedList(taken.into_column()));
120
ac.with_update_groups(UpdateGroups::WithSeriesLen);
121
Ok(ac)
122
}
123
124
fn to_field(&self, input_schema: &Schema) -> PolarsResult<Field> {
125
self.phys_expr.to_field(input_schema)
126
}
127
128
fn is_scalar(&self) -> bool {
129
self.returns_scalar
130
}
131
}
132
133