Skip to main content

polars_core/chunked_array/ops/
fill_null.rs

1use arrow::bitmap::{Bitmap, BitmapBuilder};
2use arrow::legacy::kernels::set::set_at_nulls;
3use bytemuck::Zeroable;
4use num_traits::{NumCast, One, Zero};
5use polars_utils::itertools::Itertools;
6
7use crate::prelude::*;
8
9fn err_fill_null() -> PolarsError {
10    polars_err!(ComputeError: "could not determine the fill value")
11}
12
13impl Series {
14    /// Replace None values with one of the following strategies:
15    /// * Forward fill (replace None with the previous value)
16    /// * Backward fill (replace None with the next value)
17    /// * Mean fill (replace None with the mean of the whole array)
18    /// * Min fill (replace None with the minimum of the whole array)
19    /// * Max fill (replace None with the maximum of the whole array)
20    /// * Zero fill (replace None with the value zero)
21    /// * One fill (replace None with the value one)
22    ///
23    /// *NOTE: If you want to fill the Nones with a value use the
24    /// [`fill_null` operation on `ChunkedArray<T>`](crate::chunked_array::ops::ChunkFillNullValue)*.
25    ///
26    /// # Example
27    ///
28    /// ```rust
29    /// # use polars_core::prelude::*;
30    /// fn example() -> PolarsResult<()> {
31    ///     let s = Column::new("some_missing".into(), &[Some(1), None, Some(2)]);
32    ///
33    ///     let filled = s.fill_null(FillNullStrategy::Forward(None))?;
34    ///     assert_eq!(Vec::from(filled.i32()?), &[Some(1), Some(1), Some(2)]);
35    ///
36    ///     let filled = s.fill_null(FillNullStrategy::Backward(None))?;
37    ///     assert_eq!(Vec::from(filled.i32()?), &[Some(1), Some(2), Some(2)]);
38    ///
39    ///     let filled = s.fill_null(FillNullStrategy::Min)?;
40    ///     assert_eq!(Vec::from(filled.i32()?), &[Some(1), Some(1), Some(2)]);
41    ///
42    ///     let filled = s.fill_null(FillNullStrategy::Max)?;
43    ///     assert_eq!(Vec::from(filled.i32()?), &[Some(1), Some(2), Some(2)]);
44    ///
45    ///     let filled = s.fill_null(FillNullStrategy::Mean)?;
46    ///     assert_eq!(Vec::from(filled.i32()?), &[Some(1), Some(1), Some(2)]);
47    ///
48    ///     let filled = s.fill_null(FillNullStrategy::Zero)?;
49    ///     assert_eq!(Vec::from(filled.i32()?), &[Some(1), Some(0), Some(2)]);
50    ///
51    ///     let filled = s.fill_null(FillNullStrategy::One)?;
52    ///     assert_eq!(Vec::from(filled.i32()?), &[Some(1), Some(1), Some(2)]);
53    ///
54    ///     Ok(())
55    /// }
56    /// example();
57    /// ```
58    pub fn fill_null(&self, strategy: FillNullStrategy) -> PolarsResult<Series> {
59        // Nothing to fill.
60        let nc = self.null_count();
61        if nc == 0
62            || (nc == self.len()
63                && matches!(
64                    strategy,
65                    FillNullStrategy::Forward(_)
66                        | FillNullStrategy::Backward(_)
67                        | FillNullStrategy::Max
68                        | FillNullStrategy::Min
69                        | FillNullStrategy::Mean
70                ))
71        {
72            return Ok(self.clone());
73        }
74
75        let physical_type = self.dtype().to_physical();
76
77        match strategy {
78            FillNullStrategy::Forward(None) if !physical_type.is_primitive_numeric() => {
79                fill_forward_gather(self)
80            },
81
82            // Fast path to remove limit.
83            FillNullStrategy::Forward(Some(limit)) if limit >= nc as IdxSize => {
84                self.fill_null(FillNullStrategy::Forward(None))
85            },
86            FillNullStrategy::Backward(Some(limit)) if limit >= nc as IdxSize => {
87                self.fill_null(FillNullStrategy::Backward(None))
88            },
89
90            FillNullStrategy::Forward(Some(limit)) => fill_forward_gather_limit(self, limit),
91            FillNullStrategy::Backward(None) if !physical_type.is_primitive_numeric() => {
92                fill_backward_gather(self)
93            },
94            FillNullStrategy::Backward(Some(limit)) => fill_backward_gather_limit(self, limit),
95            #[cfg(feature = "dtype-decimal")]
96            FillNullStrategy::One if self.dtype().is_decimal() => {
97                use polars_compute::decimal::i128_to_dec128;
98
99                let ca = self.decimal().unwrap();
100                let precision = ca.precision();
101                let scale = ca.scale();
102                let fill_value = i128_to_dec128(1, precision, scale).ok_or_else(|| {
103                    polars_err!(ComputeError: "value '1' is out of range for Decimal({precision}, {scale})")
104                })?;
105                let phys = ca.physical().fill_null_with_values(fill_value)?;
106                Ok(phys.into_decimal_unchecked(precision, scale).into_series())
107            },
108            _ => {
109                let logical_type = self.dtype();
110                let s = self.to_physical_repr();
111                use DataType::*;
112                let out = match s.dtype() {
113                    Boolean => fill_null_bool(s.bool().unwrap(), strategy),
114                    String => {
115                        let s = unsafe { s.cast_unchecked(&Binary)? };
116                        let out = s.fill_null(strategy)?;
117                        return unsafe { out.cast_unchecked(&String) };
118                    },
119                    Binary => {
120                        let ca = s.binary().unwrap();
121                        fill_null_binary(ca, strategy).map(|ca| ca.into_series())
122                    },
123                    dt if dt.is_primitive_numeric() => {
124                        with_match_physical_numeric_polars_type!(dt, |$T| {
125                            let ca: &ChunkedArray<$T> = s.as_ref().as_ref().as_ref();
126                                fill_null_numeric(ca, strategy).map(|ca| ca.into_series())
127                        })
128                    },
129                    dt => {
130                        polars_bail!(InvalidOperation: "fill null strategy not yet supported for dtype: {}", dt)
131                    },
132                }?;
133                unsafe { out.from_physical_unchecked(logical_type) }
134            },
135        }
136    }
137}
138
139fn fill_forward_numeric<'a, T>(ca: &'a ChunkedArray<T>) -> ChunkedArray<T>
140where
141    T: PolarsDataType,
142    T::ZeroablePhysical<'a>: Copy,
143{
144    // Compute values.
145    let values: Vec<T::ZeroablePhysical<'a>> = ca
146        .iter()
147        .scan(T::ZeroablePhysical::zeroed(), |prev, v| {
148            *prev = v.map(|v| v.into()).unwrap_or(*prev);
149            Some(*prev)
150        })
151        .collect_trusted();
152
153    // Compute bitmask.
154    let num_start_nulls = ca.first_non_null().unwrap_or(ca.len());
155    let mut bm = BitmapBuilder::with_capacity(ca.len());
156    bm.extend_constant(num_start_nulls, false);
157    bm.extend_constant(ca.len() - num_start_nulls, true);
158    ChunkedArray::from_chunk_iter_like(
159        ca,
160        [
161            T::Array::from_zeroable_vec(values, ca.dtype().to_arrow(CompatLevel::newest()))
162                .with_validity_typed(bm.into_opt_validity()),
163        ],
164    )
165}
166
167fn fill_backward_numeric<'a, T>(ca: &'a ChunkedArray<T>) -> ChunkedArray<T>
168where
169    T: PolarsDataType,
170    T::ZeroablePhysical<'a>: Copy,
171{
172    // Compute values.
173    let values: Vec<T::ZeroablePhysical<'a>> = ca
174        .iter()
175        .rev()
176        .scan(T::ZeroablePhysical::zeroed(), |prev, v| {
177            *prev = v.map(|v| v.into()).unwrap_or(*prev);
178            Some(*prev)
179        })
180        .collect_reversed();
181
182    // Compute bitmask.
183    let num_end_nulls = ca
184        .last_non_null()
185        .map(|i| ca.len() - 1 - i)
186        .unwrap_or(ca.len());
187    let mut bm = BitmapBuilder::with_capacity(ca.len());
188    bm.extend_constant(ca.len() - num_end_nulls, true);
189    bm.extend_constant(num_end_nulls, false);
190    ChunkedArray::from_chunk_iter_like(
191        ca,
192        [
193            T::Array::from_zeroable_vec(values, ca.dtype().to_arrow(CompatLevel::newest()))
194                .with_validity_typed(bm.into_opt_validity()),
195        ],
196    )
197}
198
199fn fill_null_numeric<T>(
200    ca: &ChunkedArray<T>,
201    strategy: FillNullStrategy,
202) -> PolarsResult<ChunkedArray<T>>
203where
204    T: PolarsNumericType,
205    ChunkedArray<T>: ChunkAgg<T::Native>,
206{
207    // Nothing to fill.
208    let mut out = match strategy {
209        FillNullStrategy::Min => {
210            ca.fill_null_with_values(ChunkAgg::min(ca).ok_or_else(err_fill_null)?)?
211        },
212        FillNullStrategy::Max => {
213            ca.fill_null_with_values(ChunkAgg::max(ca).ok_or_else(err_fill_null)?)?
214        },
215        FillNullStrategy::Mean => ca.fill_null_with_values(
216            ca.mean()
217                .map(|v| NumCast::from(v).unwrap())
218                .ok_or_else(err_fill_null)?,
219        )?,
220        FillNullStrategy::One => return ca.fill_null_with_values(One::one()),
221        FillNullStrategy::Zero => return ca.fill_null_with_values(Zero::zero()),
222        FillNullStrategy::Forward(None) => fill_forward_numeric(ca),
223        FillNullStrategy::Backward(None) => fill_backward_numeric(ca),
224        // Handled earlier
225        FillNullStrategy::Forward(_) => unreachable!(),
226        FillNullStrategy::Backward(_) => unreachable!(),
227    };
228    out.rename(ca.name().clone());
229    Ok(out)
230}
231
232fn fill_with_gather<F: Fn(&Bitmap) -> Vec<IdxSize>>(
233    s: &Series,
234    bits_to_idx: F,
235) -> PolarsResult<Series> {
236    let s = s.rechunk();
237    let arr = s.chunks()[0].clone();
238    let validity = arr.validity().expect("nulls");
239
240    let idx = bits_to_idx(validity);
241
242    Ok(unsafe { s.take_slice_unchecked(&idx) })
243}
244
245fn fill_forward_gather(s: &Series) -> PolarsResult<Series> {
246    fill_with_gather(s, |validity| {
247        let mut last_valid = 0;
248        validity
249            .iter()
250            .enumerate_idx()
251            .map(|(i, v)| {
252                if v {
253                    last_valid = i;
254                    i
255                } else {
256                    last_valid
257                }
258            })
259            .collect::<Vec<_>>()
260    })
261}
262
263fn fill_forward_gather_limit(s: &Series, limit: IdxSize) -> PolarsResult<Series> {
264    fill_with_gather(s, |validity| {
265        let mut last_valid = 0;
266        let mut conseq_invalid_count = 0;
267        validity
268            .iter()
269            .enumerate_idx()
270            .map(|(i, v)| {
271                if v {
272                    last_valid = i;
273                    conseq_invalid_count = 0;
274                    i
275                } else if conseq_invalid_count < limit {
276                    conseq_invalid_count += 1;
277                    last_valid
278                } else {
279                    i
280                }
281            })
282            .collect::<Vec<_>>()
283    })
284}
285
286fn fill_backward_gather(s: &Series) -> PolarsResult<Series> {
287    fill_with_gather(s, |validity| {
288        let last = validity.len() as IdxSize - 1;
289        let mut last_valid = last;
290        unsafe {
291            validity
292                .iter()
293                .rev()
294                .enumerate_idx()
295                .map(|(i, v)| {
296                    if v {
297                        last_valid = last - i;
298                        last - i
299                    } else {
300                        last_valid
301                    }
302                })
303                .trust_my_length((last + 1) as usize)
304                .collect_reversed::<Vec<_>>()
305        }
306    })
307}
308
309fn fill_backward_gather_limit(s: &Series, limit: IdxSize) -> PolarsResult<Series> {
310    fill_with_gather(s, |validity| {
311        let last = validity.len() as IdxSize - 1;
312        let mut last_valid = last;
313        let mut conseq_invalid_count = 0;
314        unsafe {
315            validity
316                .iter()
317                .rev()
318                .enumerate_idx()
319                .map(|(i, v)| {
320                    if v {
321                        last_valid = last - i;
322                        conseq_invalid_count = 0;
323                        last - i
324                    } else if conseq_invalid_count < limit {
325                        conseq_invalid_count += 1;
326                        last_valid
327                    } else {
328                        last - i
329                    }
330                })
331                .trust_my_length((last + 1) as usize)
332                .collect_reversed()
333        }
334    })
335}
336
337fn fill_null_bool(ca: &BooleanChunked, strategy: FillNullStrategy) -> PolarsResult<Series> {
338    match strategy {
339        FillNullStrategy::Min => ca
340            .fill_null_with_values(ca.min().ok_or_else(err_fill_null)?)
341            .map(|ca| ca.into_series()),
342        FillNullStrategy::Max => ca
343            .fill_null_with_values(ca.max().ok_or_else(err_fill_null)?)
344            .map(|ca| ca.into_series()),
345        FillNullStrategy::Mean => polars_bail!(opq = mean, "Boolean"),
346        FillNullStrategy::One => ca.fill_null_with_values(true).map(|ca| ca.into_series()),
347        FillNullStrategy::Zero => ca.fill_null_with_values(false).map(|ca| ca.into_series()),
348        FillNullStrategy::Forward(_) => unreachable!(),
349        FillNullStrategy::Backward(_) => unreachable!(),
350    }
351}
352
353fn fill_null_binary(ca: &BinaryChunked, strategy: FillNullStrategy) -> PolarsResult<BinaryChunked> {
354    match strategy {
355        FillNullStrategy::Min => {
356            ca.fill_null_with_values(ca.min_binary().ok_or_else(err_fill_null)?)
357        },
358        FillNullStrategy::Max => {
359            ca.fill_null_with_values(ca.max_binary().ok_or_else(err_fill_null)?)
360        },
361        FillNullStrategy::Zero => ca.fill_null_with_values(&[]),
362        FillNullStrategy::Forward(_) => unreachable!(),
363        FillNullStrategy::Backward(_) => unreachable!(),
364        strat => polars_bail!(InvalidOperation: "fill-null strategy {:?} is not supported", strat),
365    }
366}
367
368impl<T> ChunkFillNullValue<T::Native> for ChunkedArray<T>
369where
370    T: PolarsNumericType,
371{
372    fn fill_null_with_values(&self, value: T::Native) -> PolarsResult<Self> {
373        Ok(self.apply_kernel(&|arr| Box::new(set_at_nulls(arr, value))))
374    }
375}
376
377impl ChunkFillNullValue<bool> for BooleanChunked {
378    fn fill_null_with_values(&self, value: bool) -> PolarsResult<Self> {
379        self.set(&self.is_null(), Some(value))
380    }
381}
382
383impl ChunkFillNullValue<&[u8]> for BinaryChunked {
384    fn fill_null_with_values(&self, value: &[u8]) -> PolarsResult<Self> {
385        self.set(&self.is_null(), Some(value))
386    }
387}