polars_python/series/
construction.rs

1use std::borrow::Cow;
2
3use arrow::array::Array;
4use arrow::bitmap::BitmapBuilder;
5use arrow::types::NativeType;
6use numpy::{Element, PyArray1, PyArrayMethods};
7use polars_core::prelude::*;
8use polars_core::utils::CustomIterTools;
9use pyo3::exceptions::{PyTypeError, PyValueError};
10use pyo3::prelude::*;
11
12use crate::PySeries;
13use crate::conversion::any_value::py_object_to_any_value;
14use crate::conversion::{Wrap, reinterpret_vec};
15use crate::error::PyPolarsErr;
16use crate::interop::arrow::to_rust::array_to_rust;
17use crate::prelude::ObjectValue;
18use crate::utils::EnterPolarsExt;
19
20// Init with numpy arrays.
21macro_rules! init_method {
22    ($name:ident, $type:ty) => {
23        #[pymethods]
24        impl PySeries {
25            #[staticmethod]
26            fn $name(name: &str, array: &Bound<PyArray1<$type>>, _strict: bool) -> Self {
27                mmap_numpy_array(name, array)
28            }
29        }
30    };
31}
32
33init_method!(new_i8, i8);
34init_method!(new_i16, i16);
35init_method!(new_i32, i32);
36init_method!(new_i64, i64);
37init_method!(new_u8, u8);
38init_method!(new_u16, u16);
39init_method!(new_u32, u32);
40init_method!(new_u64, u64);
41
42fn mmap_numpy_array<T: Element + NativeType>(name: &str, array: &Bound<PyArray1<T>>) -> PySeries {
43    let vals = unsafe { array.as_slice().unwrap() };
44
45    let arr = unsafe { arrow::ffi::mmap::slice_and_owner(vals, array.clone().unbind()) };
46    Series::from_arrow(name.into(), arr.to_boxed())
47        .unwrap()
48        .into()
49}
50
51#[pymethods]
52impl PySeries {
53    #[staticmethod]
54    fn new_bool(
55        py: Python<'_>,
56        name: &str,
57        array: &Bound<PyArray1<bool>>,
58        _strict: bool,
59    ) -> PyResult<Self> {
60        let array = array.readonly();
61        let vals = array.as_slice().unwrap();
62        py.enter_polars_series(|| Ok(Series::new(name.into(), vals)))
63    }
64
65    #[staticmethod]
66    fn new_f32(
67        py: Python<'_>,
68        name: &str,
69        array: &Bound<PyArray1<f32>>,
70        nan_is_null: bool,
71    ) -> PyResult<Self> {
72        if nan_is_null {
73            let array = array.readonly();
74            let vals = array.as_slice().unwrap();
75            py.enter_polars_series(|| {
76                let ca: Float32Chunked = vals
77                    .iter()
78                    .map(|&val| if f32::is_nan(val) { None } else { Some(val) })
79                    .collect_trusted();
80                Ok(ca.with_name(name.into()))
81            })
82        } else {
83            Ok(mmap_numpy_array(name, array))
84        }
85    }
86
87    #[staticmethod]
88    fn new_f64(
89        py: Python<'_>,
90        name: &str,
91        array: &Bound<PyArray1<f64>>,
92        nan_is_null: bool,
93    ) -> PyResult<Self> {
94        if nan_is_null {
95            let array = array.readonly();
96            let vals = array.as_slice().unwrap();
97            py.enter_polars_series(|| {
98                let ca: Float64Chunked = vals
99                    .iter()
100                    .map(|&val| if f64::is_nan(val) { None } else { Some(val) })
101                    .collect_trusted();
102                Ok(ca.with_name(name.into()))
103            })
104        } else {
105            Ok(mmap_numpy_array(name, array))
106        }
107    }
108}
109
110#[pymethods]
111impl PySeries {
112    #[staticmethod]
113    fn new_opt_bool(name: &str, values: &Bound<PyAny>, _strict: bool) -> PyResult<Self> {
114        let len = values.len()?;
115        let mut builder = BooleanChunkedBuilder::new(name.into(), len);
116
117        for res in values.try_iter()? {
118            let value = res?;
119            if value.is_none() {
120                builder.append_null()
121            } else {
122                let v = value.extract::<bool>()?;
123                builder.append_value(v)
124            }
125        }
126
127        let ca = builder.finish();
128        let s = ca.into_series();
129        Ok(s.into())
130    }
131}
132
133fn new_primitive<'py, T>(
134    name: &str,
135    values: &Bound<'py, PyAny>,
136    _strict: bool,
137) -> PyResult<PySeries>
138where
139    T: PolarsNumericType,
140    T::Native: FromPyObject<'py>,
141{
142    let len = values.len()?;
143    let mut builder = PrimitiveChunkedBuilder::<T>::new(name.into(), len);
144
145    for res in values.try_iter()? {
146        let value = res?;
147        if value.is_none() {
148            builder.append_null()
149        } else {
150            let v = value.extract::<T::Native>()?;
151            builder.append_value(v)
152        }
153    }
154
155    let ca = builder.finish();
156    let s = ca.into_series();
157    Ok(s.into())
158}
159
160// Init with lists that can contain Nones
161macro_rules! init_method_opt {
162    ($name:ident, $type:ty, $native: ty) => {
163        #[pymethods]
164        impl PySeries {
165            #[staticmethod]
166            fn $name(name: &str, obj: &Bound<PyAny>, strict: bool) -> PyResult<Self> {
167                new_primitive::<$type>(name, obj, strict)
168            }
169        }
170    };
171}
172
173init_method_opt!(new_opt_u8, UInt8Type, u8);
174init_method_opt!(new_opt_u16, UInt16Type, u16);
175init_method_opt!(new_opt_u32, UInt32Type, u32);
176init_method_opt!(new_opt_u64, UInt64Type, u64);
177init_method_opt!(new_opt_i8, Int8Type, i8);
178init_method_opt!(new_opt_i16, Int16Type, i16);
179init_method_opt!(new_opt_i32, Int32Type, i32);
180init_method_opt!(new_opt_i64, Int64Type, i64);
181init_method_opt!(new_opt_i128, Int128Type, i64);
182init_method_opt!(new_opt_f32, Float32Type, f32);
183init_method_opt!(new_opt_f64, Float64Type, f64);
184
185fn convert_to_avs(
186    values: &Bound<'_, PyAny>,
187    strict: bool,
188    allow_object: bool,
189) -> PyResult<Vec<AnyValue<'static>>> {
190    values
191        .try_iter()?
192        .map(|v| py_object_to_any_value(&(v?).as_borrowed(), strict, allow_object))
193        .collect()
194}
195
196#[pymethods]
197impl PySeries {
198    #[staticmethod]
199    fn new_from_any_values(name: &str, values: &Bound<PyAny>, strict: bool) -> PyResult<Self> {
200        let any_values_result = values
201            .try_iter()?
202            .map(|v| py_object_to_any_value(&(v?).as_borrowed(), strict, true))
203            .collect::<PyResult<Vec<AnyValue>>>();
204
205        let result = any_values_result.and_then(|avs| {
206            let s = Series::from_any_values(name.into(), avs.as_slice(), strict).map_err(|e| {
207                PyTypeError::new_err(format!(
208                    "{e}\n\nHint: Try setting `strict=False` to allow passing data with mixed types."
209                ))
210            })?;
211            Ok(s.into())
212        });
213
214        // Fall back to Object type for non-strict construction.
215        if !strict && result.is_err() {
216            return Python::with_gil(|py| {
217                let objects = values
218                    .try_iter()?
219                    .map(|v| v?.extract())
220                    .collect::<PyResult<Vec<ObjectValue>>>()?;
221                Ok(Self::new_object(py, name, objects, strict))
222            });
223        }
224
225        result
226    }
227
228    #[staticmethod]
229    fn new_from_any_values_and_dtype(
230        name: &str,
231        values: &Bound<PyAny>,
232        dtype: Wrap<DataType>,
233        strict: bool,
234    ) -> PyResult<Self> {
235        let avs = convert_to_avs(values, strict, false)?;
236        let s = Series::from_any_values_and_dtype(name.into(), avs.as_slice(), &dtype.0, strict)
237            .map_err(|e| {
238                PyTypeError::new_err(format!(
239                "{e}\n\nHint: Try setting `strict=False` to allow passing data with mixed types."
240            ))
241            })?;
242        Ok(s.into())
243    }
244
245    #[staticmethod]
246    fn new_str(name: &str, values: &Bound<PyAny>, _strict: bool) -> PyResult<Self> {
247        let len = values.len()?;
248        let mut builder = StringChunkedBuilder::new(name.into(), len);
249
250        for res in values.try_iter()? {
251            let value = res?;
252            if value.is_none() {
253                builder.append_null()
254            } else {
255                let v = value.extract::<Cow<str>>()?;
256                builder.append_value(v)
257            }
258        }
259
260        let ca = builder.finish();
261        let s = ca.into_series();
262        Ok(s.into())
263    }
264
265    #[staticmethod]
266    fn new_binary(name: &str, values: &Bound<PyAny>, _strict: bool) -> PyResult<Self> {
267        let len = values.len()?;
268        let mut builder = BinaryChunkedBuilder::new(name.into(), len);
269
270        for res in values.try_iter()? {
271            let value = res?;
272            if value.is_none() {
273                builder.append_null()
274            } else {
275                let v = value.extract::<&[u8]>()?;
276                builder.append_value(v)
277            }
278        }
279
280        let ca = builder.finish();
281        let s = ca.into_series();
282        Ok(s.into())
283    }
284
285    #[staticmethod]
286    fn new_decimal(name: &str, values: &Bound<PyAny>, strict: bool) -> PyResult<Self> {
287        Self::new_from_any_values(name, values, strict)
288    }
289
290    #[staticmethod]
291    fn new_series_list(name: &str, values: Vec<Option<PySeries>>, _strict: bool) -> PyResult<Self> {
292        let series = reinterpret_vec(values);
293        if let Some(s) = series.iter().flatten().next() {
294            if s.dtype().is_object() {
295                return Err(PyValueError::new_err(
296                    "list of objects isn't supported; try building a 'object' only series",
297                ));
298            }
299        }
300        Ok(Series::new(name.into(), series).into())
301    }
302
303    #[staticmethod]
304    #[pyo3(signature = (name, values, strict, dtype))]
305    fn new_array(
306        name: &str,
307        values: &Bound<PyAny>,
308        strict: bool,
309        dtype: Wrap<DataType>,
310    ) -> PyResult<Self> {
311        Self::new_from_any_values_and_dtype(name, values, dtype, strict)
312    }
313
314    #[staticmethod]
315    pub fn new_object(py: Python<'_>, name: &str, values: Vec<ObjectValue>, _strict: bool) -> Self {
316        #[cfg(feature = "object")]
317        {
318            let mut validity = BitmapBuilder::with_capacity(values.len());
319            values.iter().for_each(|v| {
320                let is_valid = !v.inner.is_none(py);
321                // SAFETY: we can ensure that validity has correct capacity.
322                unsafe { validity.push_unchecked(is_valid) };
323            });
324            // Object builder must be registered. This is done on import.
325            let ca = ObjectChunked::<ObjectValue>::new_from_vec_and_validity(
326                name.into(),
327                values,
328                validity.into_opt_validity(),
329            );
330            let s = ca.into_series();
331            s.into()
332        }
333        #[cfg(not(feature = "object"))]
334        panic!("activate 'object' feature")
335    }
336
337    #[staticmethod]
338    fn new_null(name: &str, values: &Bound<PyAny>, _strict: bool) -> PyResult<Self> {
339        let len = values.len()?;
340        Ok(Series::new_null(name.into(), len).into())
341    }
342
343    #[staticmethod]
344    fn from_arrow(name: &str, array: &Bound<PyAny>) -> PyResult<Self> {
345        let arr = array_to_rust(array)?;
346
347        match arr.dtype() {
348            ArrowDataType::LargeList(_) => {
349                let array = arr.as_any().downcast_ref::<LargeListArray>().unwrap();
350                let fast_explode = array.offsets().as_slice().windows(2).all(|w| w[0] != w[1]);
351
352                let mut out = ListChunked::with_chunk(name.into(), array.clone());
353                if fast_explode {
354                    out.set_fast_explode()
355                }
356                Ok(out.into_series().into())
357            },
358            _ => {
359                let series: Series =
360                    Series::try_new(name.into(), arr).map_err(PyPolarsErr::from)?;
361                Ok(series.into())
362            },
363        }
364    }
365}