polars_core/chunked_array/ops/aggregate/
var.rs

1use polars_compute::var_cov::VarState;
2
3use super::*;
4
5pub trait VarAggSeries {
6    /// Get the variance of the [`ChunkedArray`] as a new [`Series`] of length 1.
7    fn var_reduce(&self, ddof: u8) -> Scalar;
8    /// Get the standard deviation of the [`ChunkedArray`] as a new [`Series`] of length 1.
9    fn std_reduce(&self, ddof: u8) -> Scalar;
10}
11
12impl<T> ChunkVar for ChunkedArray<T>
13where
14    T: PolarsNumericType,
15    ChunkedArray<T>: ChunkAgg<T::Native>,
16{
17    fn var(&self, ddof: u8) -> Option<f64> {
18        let mut out = VarState::default();
19        for arr in self.downcast_iter() {
20            out.combine(&polars_compute::var_cov::var(arr))
21        }
22        out.finalize(ddof)
23    }
24
25    fn std(&self, ddof: u8) -> Option<f64> {
26        self.var(ddof).map(|var| var.sqrt())
27    }
28}
29
30impl ChunkVar for StringChunked {}
31impl ChunkVar for ListChunked {}
32#[cfg(feature = "dtype-array")]
33impl ChunkVar for ArrayChunked {}
34#[cfg(feature = "object")]
35impl<T: PolarsObject> ChunkVar for ObjectChunked<T> {}
36impl ChunkVar for BooleanChunked {}