Skip to main content

polars_core/frame/column/
compare.rs

1use polars_arrow::array::BooleanArray;
2use polars_arrow::bitmap::Bitmap;
3use polars_arrow::datatypes::ArrowDataType;
4use polars_error::{PolarsResult, polars_ensure};
5use polars_utils::broadcast::broadcast_len;
6use polars_utils::pl_str::PlSmallStr;
7
8use super::{
9    BooleanChunked, ChunkCompareEq, ChunkCompareIneq, ChunkExpandAtIndex, Column, DictionaryColumn,
10    IntoSeries, Series,
11};
12use crate::prelude::{ChunkFullNull, StringChunked};
13
14/// `op` evaluated on each used value of `column` and spread to its rows.
15fn dictionary_mask(
16    column: &DictionaryColumn,
17    op: &dyn Fn(&Series) -> PolarsResult<BooleanChunked>,
18) -> PolarsResult<BooleanChunked> {
19    if column.dict().len() <= column.len() {
20        match dictionary_lookup_mask(column, op) {
21            Ok(mask) => return Ok(mask),
22            Err(err) => {
23                // A value no row uses may fail where the used ones don't; that falls back to the
24                // used ones. An error without any values (e.g. of the dtypes) is returned at once.
25                let empty = StringChunked::full_null(column.name().clone(), 0).into_series();
26                if op(&empty).is_err() {
27                    return Err(err);
28                }
29            },
30        }
31    }
32    let out = column.apply_elementwise(|values| op(values).map(|ca| ca.into_series()))?;
33    Ok(out.bool()?.clone())
34}
35
36/// `op` evaluated once on every dictionary value and on a null, then looked up per row by code.
37fn dictionary_lookup_mask(
38    column: &DictionaryColumn,
39    op: &dyn Fn(&Series) -> PolarsResult<BooleanChunked>,
40) -> PolarsResult<BooleanChunked> {
41    let n = column.dict().len();
42    let mut values =
43        StringChunked::with_chunk(column.name().clone(), column.dict().values().clone());
44    values.append(&StringChunked::full_null(PlSmallStr::EMPTY, 1))?;
45    let table = op(&values.into_series())?;
46    let table = table.rechunk();
47    polars_ensure!(
48        table.len() == n + 1,
49        ComputeError: "comparison changed the length of a dictionary column"
50    );
51    let name = table.name().clone();
52    let table = table.downcast_as_array();
53    let bits: Vec<bool> = table.values().iter().collect();
54    let valid: Option<Vec<bool>> = table.validity().map(|v| v.iter().collect());
55
56    let codes = column.codes().rechunk();
57    let codes = codes.downcast_as_array();
58    // SAFETY: valid codes are below `n` (invariant) and the tables have `n + 1` entries.
59    let (values, validity) = match codes.validity().filter(|v| v.unset_bits() > 0) {
60        None => {
61            let gather = |table: &[bool]| {
62                Bitmap::from_trusted_len_iter(
63                    codes
64                        .values()
65                        .iter()
66                        .map(|c| unsafe { *table.get_unchecked(*c as usize) }),
67                )
68            };
69            let validity = valid
70                .as_deref()
71                .filter(|valid| !valid[..n].iter().all(|v| *v))
72                .map(gather);
73            (gather(&bits), validity)
74        },
75        Some(code_validity) => {
76            // Null rows look up the last entry, the result for a null.
77            let gather = |table: &[bool]| {
78                Bitmap::from_trusted_len_iter(codes.values().iter().zip(code_validity).map(
79                    |(c, is_valid)| unsafe {
80                        *table.get_unchecked(if is_valid { *c as usize } else { n })
81                    },
82                ))
83            };
84            (gather(&bits), valid.as_deref().map(gather))
85        },
86    };
87    let arr = BooleanArray::new(ArrowDataType::Boolean, values, validity);
88    Ok(BooleanChunked::with_chunk(name, arr))
89}
90
91type CompareFn = fn(&Series, &Series) -> PolarsResult<BooleanChunked>;
92
93fn compare_broadcasting(lhs: &Column, rhs: &Column, op: CompareFn) -> PolarsResult<BooleanChunked> {
94    match (lhs, rhs) {
95        // Compare each used dictionary value with the constant once. Only when the result has
96        // the dictionary column's length: a length-1 one broadcasts to a longer constant.
97        (Column::Dictionary(lhs), rhs)
98            if rhs.len() == 1 || (rhs.len() == lhs.len() && rhs.as_scalar_column().is_some()) =>
99        {
100            let rhs = rhs.as_materialized_series_maintain_scalar();
101            dictionary_mask(lhs, &|values| op(values, &rhs))
102        },
103        (lhs, Column::Dictionary(rhs))
104            if lhs.len() == 1 || (lhs.len() == rhs.len() && lhs.as_scalar_column().is_some()) =>
105        {
106            let lhs = lhs.as_materialized_series_maintain_scalar();
107            dictionary_mask(rhs, &|values| op(&lhs, values))
108        },
109        (Column::Series(lhs), Column::Scalar(rhs)) => op(lhs, &rhs.as_single_value_series()),
110        (Column::Scalar(lhs), Column::Series(rhs)) => op(&lhs.as_single_value_series(), rhs),
111        (Column::Scalar(lhs), Column::Scalar(rhs)) => {
112            let length = broadcast_len([lhs, rhs])?;
113            op(&lhs.as_single_value_series(), &rhs.as_single_value_series()).map(|ca| {
114                if ca.is_empty() {
115                    ca
116                } else {
117                    ca.new_from_index(0, length)
118                }
119            })
120        },
121        (lhs, rhs) => op(lhs.as_materialized_series(), rhs.as_materialized_series()),
122    }
123}
124
125impl ChunkCompareEq<&Column> for Column {
126    type Item = PolarsResult<BooleanChunked>;
127
128    /// Create a boolean mask by checking for equality.
129    fn equal(&self, rhs: &Column) -> PolarsResult<BooleanChunked> {
130        compare_broadcasting(self, rhs, |l: &Series, r: &Series| {
131            <Series as ChunkCompareEq<&Series>>::equal(l, r)
132        })
133    }
134
135    /// Create a boolean mask by checking for equality.
136    fn equal_missing(&self, rhs: &Column) -> PolarsResult<BooleanChunked> {
137        compare_broadcasting(self, rhs, |l: &Series, r: &Series| {
138            <Series as ChunkCompareEq<&Series>>::equal_missing(l, r)
139        })
140    }
141
142    /// Create a boolean mask by checking for inequality.
143    fn not_equal(&self, rhs: &Column) -> PolarsResult<BooleanChunked> {
144        compare_broadcasting(self, rhs, |l: &Series, r: &Series| {
145            <Series as ChunkCompareEq<&Series>>::not_equal(l, r)
146        })
147    }
148
149    /// Create a boolean mask by checking for inequality.
150    fn not_equal_missing(&self, rhs: &Column) -> PolarsResult<BooleanChunked> {
151        compare_broadcasting(self, rhs, |l: &Series, r: &Series| {
152            <Series as ChunkCompareEq<&Series>>::not_equal_missing(l, r)
153        })
154    }
155}
156
157impl ChunkCompareIneq<&Column> for Column {
158    type Item = PolarsResult<BooleanChunked>;
159
160    /// Create a boolean mask by checking if self > rhs.
161    fn gt(&self, rhs: &Column) -> PolarsResult<BooleanChunked> {
162        compare_broadcasting(self, rhs, |l: &Series, r: &Series| {
163            <Series as ChunkCompareIneq<&Series>>::gt(l, r)
164        })
165    }
166
167    /// Create a boolean mask by checking if self >= rhs.
168    fn gt_eq(&self, rhs: &Column) -> PolarsResult<BooleanChunked> {
169        compare_broadcasting(self, rhs, |l: &Series, r: &Series| {
170            <Series as ChunkCompareIneq<&Series>>::gt_eq(l, r)
171        })
172    }
173
174    /// Create a boolean mask by checking if self < rhs.
175    fn lt(&self, rhs: &Column) -> PolarsResult<BooleanChunked> {
176        compare_broadcasting(self, rhs, |l: &Series, r: &Series| {
177            <Series as ChunkCompareIneq<&Series>>::lt(l, r)
178        })
179    }
180
181    /// Create a boolean mask by checking if self <= rhs.
182    fn lt_eq(&self, rhs: &Column) -> PolarsResult<BooleanChunked> {
183        compare_broadcasting(self, rhs, |l: &Series, r: &Series| {
184            <Series as ChunkCompareIneq<&Series>>::lt_eq(l, r)
185        })
186    }
187}