Skip to main content

polars_core/chunked_array/
to_vec.rs

1use either::Either;
2use polars_compute::filter::filter_values;
3
4use crate::prelude::*;
5
6impl<T: PolarsNumericType> ChunkedArray<T> {
7    /// Convert to a [`Vec`] of [`Option<T::Native>`].
8    pub fn to_vec(&self) -> Vec<Option<T::Native>> {
9        let mut buf = Vec::with_capacity(self.len());
10        for arr in self.downcast_iter() {
11            buf.extend(arr.into_iter().map(|v| v.copied()))
12        }
13        buf
14    }
15
16    /// Convert to a [`Vec`] but don't return [`Option<T::Native>`] if there are no null values
17    pub fn to_vec_null_aware(&self) -> Either<Vec<T::Native>, Vec<Option<T::Native>>> {
18        if self.null_count() == 0 {
19            let mut buf = Vec::with_capacity(self.len());
20
21            for arr in self.downcast_iter() {
22                buf.extend_from_slice(arr.values())
23            }
24            Either::Left(buf)
25        } else {
26            Either::Right(self.to_vec())
27        }
28    }
29
30    /// Convert to a [`Vec`] of the non-null values.
31    pub fn to_vec_non_null(&self) -> Vec<T::Native> {
32        let filtered = |arr: &PrimitiveArray<T::Native>| match arr.validity() {
33            Some(validity) if validity.unset_bits() > 0 => {
34                Some(filter_values(arr.values(), validity))
35            },
36            _ => None,
37        };
38        if self.chunks().len() == 1 {
39            let arr = self.downcast_iter().next().unwrap();
40            return filtered(arr).unwrap_or_else(|| arr.values().as_slice().to_vec());
41        }
42        let mut vals = Vec::with_capacity(self.len() - self.null_count());
43        for arr in self.downcast_iter() {
44            match filtered(arr) {
45                Some(nonnull) => vals.extend_from_slice(&nonnull),
46                None => vals.extend_from_slice(arr.values()),
47            }
48        }
49        vals
50    }
51}