Skip to main content

polars_ops/series/ops/
horizontal.rs

1use std::borrow::Cow;
2
3use polars_core::chunked_array::cast::CastOptions;
4use polars_core::prelude::*;
5use polars_core::runtime::RAYON;
6use polars_core::series::arithmetic::coerce_lhs_rhs;
7use polars_core::utils::dtypes_to_supertype;
8use polars_core::with_match_physical_numeric_polars_type;
9use polars_utils::broadcast::broadcast_len;
10use polars_utils::min_max::MinMax;
11use rayon::iter::{IntoParallelIterator, IntoParallelRefIterator, ParallelIterator};
12
13pub trait MinMaxHorizontal {
14    /// Aggregate the column horizontally to their min values.
15    fn min_horizontal(&self) -> PolarsResult<Option<Column>>;
16    /// Aggregate the column horizontally to their max values.
17    fn max_horizontal(&self) -> PolarsResult<Option<Column>>;
18}
19
20impl MinMaxHorizontal for DataFrame {
21    fn min_horizontal(&self) -> PolarsResult<Option<Column>> {
22        min_horizontal(self.columns())
23    }
24    fn max_horizontal(&self) -> PolarsResult<Option<Column>> {
25        max_horizontal(self.columns())
26    }
27}
28
29#[derive(Copy, Clone, Debug, PartialEq)]
30pub enum NullStrategy {
31    Ignore,
32    Propagate,
33}
34
35pub trait SumMeanHorizontal {
36    /// Sum all values horizontally across columns.
37    fn sum_horizontal(&self, null_strategy: NullStrategy) -> PolarsResult<Option<Column>>;
38
39    /// Compute the mean of all numeric values horizontally across columns.
40    fn mean_horizontal(&self, null_strategy: NullStrategy) -> PolarsResult<Option<Column>>;
41}
42
43impl SumMeanHorizontal for DataFrame {
44    fn sum_horizontal(&self, null_strategy: NullStrategy) -> PolarsResult<Option<Column>> {
45        sum_horizontal(self.columns(), null_strategy)
46    }
47    fn mean_horizontal(&self, null_strategy: NullStrategy) -> PolarsResult<Option<Column>> {
48        mean_horizontal(self.columns(), null_strategy)
49    }
50}
51
52fn min_binary<T>(left: &ChunkedArray<T>, right: &ChunkedArray<T>) -> ChunkedArray<T>
53where
54    T: PolarsNumericType,
55    T::Native: MinMax,
56{
57    if !left.has_nulls() && !right.has_nulls() {
58        arity::broadcast_binary_elementwise_values(left, right, MinMax::min_ignore_nan)
59    } else {
60        arity::broadcast_binary_elementwise(left, right, |opt_l, opt_r| match (opt_l, opt_r) {
61            (Some(l), Some(r)) => Some(l.min_ignore_nan(r)),
62            (Some(x), None) | (None, Some(x)) => Some(x),
63            (None, None) => None,
64        })
65    }
66}
67
68fn max_binary<T>(left: &ChunkedArray<T>, right: &ChunkedArray<T>) -> ChunkedArray<T>
69where
70    T: PolarsNumericType,
71    T::Native: MinMax,
72{
73    if !left.has_nulls() && !right.has_nulls() {
74        arity::broadcast_binary_elementwise_values(left, right, MinMax::max_ignore_nan)
75    } else {
76        arity::broadcast_binary_elementwise(left, right, |opt_l, opt_r| match (opt_l, opt_r) {
77            (Some(l), Some(r)) => Some(l.max_ignore_nan(r)),
78            (Some(x), None) | (None, Some(x)) => Some(x),
79            (None, None) => None,
80        })
81    }
82}
83
84fn min_max_binary_columns(left: &Column, right: &Column, min: bool) -> PolarsResult<Column> {
85    if left.dtype().to_physical().is_primitive_numeric()
86        && right.dtype().to_physical().is_primitive_numeric()
87    {
88        let left_s = left.as_materialized_series_maintain_scalar();
89        let right_s = right.as_materialized_series_maintain_scalar();
90        let (lhs, rhs) = coerce_lhs_rhs(&left_s, &right_s)?;
91        let logical = lhs.dtype();
92
93        let lhs = lhs.to_physical_repr();
94        let rhs = rhs.to_physical_repr();
95
96        with_match_physical_numeric_polars_type!(lhs.dtype(), |$T| {
97            let a: &ChunkedArray<$T> = lhs.as_ref().as_ref().as_ref();
98            let b: &ChunkedArray<$T> = rhs.as_ref().as_ref().as_ref();
99
100            unsafe {
101                if min {
102                    min_binary(a, b).into_series().from_physical_unchecked(logical)
103                } else {
104                    max_binary(a, b).into_series().from_physical_unchecked(logical)
105                }
106            }
107        })
108        .map(Column::from)
109    } else {
110        let mut mask = if min {
111            left.lt(right)?
112        } else {
113            left.gt(right)?
114        };
115        if left.has_nulls() {
116            mask = mask & left.is_not_null();
117        }
118        if right.has_nulls() {
119            mask = mask | right.is_null();
120        }
121        left.zip_with(&mask, right)
122    }
123}
124
125pub fn max_horizontal(columns: &[Column]) -> PolarsResult<Option<Column>> {
126    broadcast_len(columns.iter()).context("max_horizontal")?;
127
128    let max_fn = |acc: &Column, s: &Column| min_max_binary_columns(acc, s, false);
129
130    match columns.len() {
131        0 => Ok(None),
132        1 => Ok(Some(columns[0].clone())),
133        2 => max_fn(&columns[0], &columns[1]).map(Some),
134        _ => {
135            // the try_reduce_with is a bit slower in parallelism,
136            // but I don't think it matters here as we parallelize over columns, not over elements
137            RAYON.install(|| {
138                columns
139                    .par_iter()
140                    .map(|s| Ok(Cow::Borrowed(s)))
141                    .try_reduce_with(|l, r| max_fn(&l, &r).map(Cow::Owned))
142                    // we can unwrap the option, because we are certain there is a column
143                    // we started this operation on 3 columns
144                    .unwrap()
145                    .map(|cow| Some(cow.into_owned()))
146            })
147        },
148    }
149}
150
151pub fn min_horizontal(columns: &[Column]) -> PolarsResult<Option<Column>> {
152    broadcast_len(columns.iter()).context("min_horizontal")?;
153
154    let min_fn = |acc: &Column, s: &Column| min_max_binary_columns(acc, s, true);
155
156    match columns.len() {
157        0 => Ok(None),
158        1 => Ok(Some(columns[0].clone())),
159        2 => min_fn(&columns[0], &columns[1]).map(Some),
160        _ => {
161            // the try_reduce_with is a bit slower in parallelism,
162            // but I don't think it matters here as we parallelize over columns, not over elements
163            RAYON.install(|| {
164                columns
165                    .par_iter()
166                    .map(|s| Ok(Cow::Borrowed(s)))
167                    .try_reduce_with(|l, r| min_fn(&l, &r).map(Cow::Owned))
168                    // we can unwrap the option, because we are certain there is a column
169                    // we started this operation on 3 columns
170                    .unwrap()
171                    .map(|cow| Some(cow.into_owned()))
172            })
173        },
174    }
175}
176
177pub fn sum_horizontal(
178    columns: &[Column],
179    null_strategy: NullStrategy,
180) -> PolarsResult<Option<Column>> {
181    broadcast_len(columns.iter()).context("sum_horizontal")?;
182    let ignore_nulls = null_strategy == NullStrategy::Ignore;
183
184    let apply_null_strategy = |s: Series| -> PolarsResult<Series> {
185        if ignore_nulls && s.null_count() > 0 {
186            s.fill_null(FillNullStrategy::Zero)
187        } else {
188            Ok(s)
189        }
190    };
191
192    let sum_fn = |acc: Series, s: Series| -> PolarsResult<Series> {
193        let acc: Series = apply_null_strategy(acc)?;
194        let s = apply_null_strategy(s)?;
195        // This will do owned arithmetic and can be mutable
196        std::ops::Add::add(acc, s)
197    };
198
199    // @scalar-opt
200    let non_null_cols = columns
201        .iter()
202        .filter(|x| x.dtype() != &DataType::Null)
203        .map(|c| c.as_materialized_series())
204        .collect::<Vec<_>>();
205
206    // If we have any null columns and null strategy is not `Ignore`, we can return immediately.
207    if !ignore_nulls && non_null_cols.len() < columns.len() {
208        // We must determine the correct return dtype.
209        let return_dtype = match dtypes_to_supertype(non_null_cols.iter().map(|c| c.dtype()))? {
210            DataType::Boolean => IDX_DTYPE,
211            dt => dt,
212        };
213        return Ok(Some(Column::full_null(
214            columns[0].name().clone(),
215            columns[0].len(),
216            &return_dtype,
217        )));
218    }
219
220    match non_null_cols.len() {
221        0 => {
222            if columns.is_empty() {
223                Ok(None)
224            } else {
225                // all columns are null dtype, so result is null dtype
226                Ok(Some(columns[0].clone()))
227            }
228        },
229        1 => Ok(Some(
230            apply_null_strategy(if non_null_cols[0].dtype() == &DataType::Boolean {
231                non_null_cols[0].cast(&IDX_DTYPE)?
232            } else {
233                non_null_cols[0].clone()
234            })?
235            .into(),
236        )),
237        2 => sum_fn(non_null_cols[0].clone(), non_null_cols[1].clone())
238            .map(Column::from)
239            .map(Some),
240        _ => {
241            // the try_reduce_with is a bit slower in parallelism,
242            // but I don't think it matters here as we parallelize over columns, not over elements
243            let out = RAYON.install(|| {
244                non_null_cols
245                    .into_par_iter()
246                    .cloned()
247                    .map(Ok)
248                    .try_reduce_with(sum_fn)
249                    // We can unwrap because we started with at least 3 columns, so we always get a Some
250                    .unwrap()
251            });
252            out.map(Column::from).map(Some)
253        },
254    }
255}
256
257pub fn mean_horizontal(
258    columns: &[Column],
259    null_strategy: NullStrategy,
260) -> PolarsResult<Option<Column>> {
261    broadcast_len(columns.iter()).context("mean_horizontal")?;
262
263    let (numeric_columns, non_numeric_columns): (Vec<_>, Vec<_>) = columns.iter().partition(|s| {
264        let dtype = s.dtype();
265        dtype.is_primitive_numeric() || dtype.is_decimal() || dtype.is_bool() || dtype.is_null()
266    });
267
268    if !non_numeric_columns.is_empty() {
269        let col = non_numeric_columns.first().cloned();
270        polars_bail!(
271            InvalidOperation: "'horizontal_mean' expects numeric expressions, found {:?} (dtype={})",
272            col.unwrap().name(),
273            col.unwrap().dtype(),
274        );
275    }
276    let columns = numeric_columns.into_iter().cloned().collect::<Vec<_>>();
277    let num_rows = columns.len();
278    match num_rows {
279        0 => Ok(None),
280        1 => Ok(Some(match columns[0].dtype() {
281            dt if !matches!(dt, DataType::Float16 | DataType::Float32) && !dt.is_decimal() => {
282                columns[0].cast(&DataType::Float64)?
283            },
284            _ => columns[0].clone(),
285        })),
286        _ => {
287            let sum = || sum_horizontal(columns.as_slice(), null_strategy);
288            let null_count = || {
289                columns
290                    .par_iter()
291                    .map(|c| {
292                        c.is_null()
293                            .into_column()
294                            .cast_with_options(&DataType::UInt32, CastOptions::NonStrict)
295                    })
296                    .reduce_with(|l, r| {
297                        let l = l?;
298                        let r = r?;
299                        let result = std::ops::Add::add(&l, &r)?;
300                        PolarsResult::Ok(result)
301                    })
302                    // we can unwrap the option, because we are certain there is a column
303                    // we started this operation on 2 columns
304                    .unwrap()
305            };
306
307            let (sum, null_count) = RAYON.install(|| rayon::join(sum, null_count));
308            let sum = sum?;
309            let null_count = null_count?;
310
311            // value lengths: len - null_count
312            let value_length: UInt32Chunked = (Column::new_scalar(
313                PlSmallStr::EMPTY,
314                Scalar::from(num_rows as u32),
315                null_count.len(),
316            ) - null_count)?
317                .u32()
318                .unwrap()
319                .clone();
320
321            // make sure that we do not divide by zero
322            // by replacing with None
323            let dt = sum
324                .as_ref()
325                .map(Column::dtype)
326                .filter(|dt| matches!(dt, DataType::Float16 | DataType::Float32))
327                .unwrap_or(&DataType::Float64);
328            let value_length = value_length
329                .set(&value_length.equal(0), None)?
330                .into_column()
331                .cast(dt)?;
332
333            sum.map(|sum| std::ops::Div::div(&sum, &value_length))
334                .transpose()
335        },
336    }
337}
338
339pub fn coalesce_columns(s: &[Column]) -> PolarsResult<Column> {
340    // TODO! this can be faster if we have more than two inputs.
341    polars_ensure!(!s.is_empty(), NoData: "cannot coalesce empty list");
342    let mut out = s[0].clone();
343    for s in s {
344        if !out.null_count() == 0 {
345            return Ok(out);
346        } else {
347            let mask = out.is_not_null();
348            out = out
349                .as_materialized_series()
350                .zip_with_same_type(&mask, s.as_materialized_series())?
351                .into();
352        }
353    }
354    Ok(out)
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360
361    #[test]
362    #[cfg_attr(miri, ignore)]
363    fn test_horizontal_agg() {
364        let a = Column::new("a".into(), [1, 2, 6]);
365        let b = Column::new("b".into(), [Some(1), None, None]);
366        let c = Column::new("c".into(), [Some(4), None, Some(3)]);
367
368        let df = DataFrame::new_infer_height(vec![a, b, c]).unwrap();
369        assert_eq!(
370            Vec::from(
371                df.mean_horizontal(NullStrategy::Ignore)
372                    .unwrap()
373                    .unwrap()
374                    .f64()
375                    .unwrap()
376            ),
377            &[Some(2.0), Some(2.0), Some(4.5)]
378        );
379        assert_eq!(
380            Vec::from(
381                df.sum_horizontal(NullStrategy::Ignore)
382                    .unwrap()
383                    .unwrap()
384                    .i32()
385                    .unwrap()
386            ),
387            &[Some(6), Some(2), Some(9)]
388        );
389        assert_eq!(
390            Vec::from(df.min_horizontal().unwrap().unwrap().i32().unwrap()),
391            &[Some(1), Some(2), Some(3)]
392        );
393        assert_eq!(
394            Vec::from(df.max_horizontal().unwrap().unwrap().i32().unwrap()),
395            &[Some(4), Some(2), Some(6)]
396        );
397    }
398}