Skip to main content

polars_core/series/
from.rs

1use arrow::datatypes::{IntervalUnit, Metadata};
2use arrow::offset::OffsetsBuffer;
3#[cfg(any(
4    feature = "dtype-date",
5    feature = "dtype-datetime",
6    feature = "dtype-time",
7    feature = "dtype-duration"
8))]
9use arrow::temporal_conversions::*;
10use arrow::types::months_days_ns;
11use polars_compute::cast::cast_unchecked as cast;
12#[cfg(feature = "dtype-decimal")]
13use polars_compute::decimal::dec128_fits;
14use polars_error::feature_gated;
15use polars_utils::itertools::Itertools;
16
17use crate::chunked_array::cast::{CastOptions, cast_chunks};
18#[cfg(feature = "object")]
19use crate::chunked_array::object::extension::polars_extension::PolarsExtension;
20#[cfg(feature = "object")]
21use crate::chunked_array::object::registry::get_object_builder;
22use crate::config::check_allow_importing_interval_as_struct;
23use crate::prelude::*;
24
25impl Series {
26    pub fn from_array<A: ParameterFreeDtypeStaticArray>(name: PlSmallStr, array: A) -> Self {
27        unsafe {
28            Self::from_chunks_and_dtype_unchecked(
29                name,
30                vec![Box::new(array)],
31                &DataType::from_arrow_dtype(&A::get_dtype()),
32            )
33        }
34    }
35
36    pub fn from_chunk_and_dtype(
37        name: PlSmallStr,
38        chunk: ArrayRef,
39        dtype: &DataType,
40    ) -> PolarsResult<Self> {
41        if &dtype.to_physical().to_arrow(CompatLevel::newest()) != chunk.dtype() {
42            polars_bail!(
43                InvalidOperation: "cannot create a series of type '{dtype}' of arrow chunk with type '{:?}'",
44                chunk.dtype()
45            );
46        }
47
48        // SAFETY: We check that the datatype matches.
49        let series = unsafe { Self::from_chunks_and_dtype_unchecked(name, vec![chunk], dtype) };
50        Ok(series)
51    }
52
53    /// Takes chunks and a polars datatype and constructs the Series.
54    /// This is faster than creating from chunks and an arrow datatype because there is no
55    /// casting involved.
56    ///
57    /// # Safety
58    ///
59    /// The caller must ensure that the given `dtype`'s physical type matches all the `ArrayRef` dtypes.
60    pub unsafe fn from_chunks_and_dtype_unchecked(
61        name: PlSmallStr,
62        chunks: Vec<ArrayRef>,
63        dtype: &DataType,
64    ) -> Self {
65        use DataType::*;
66        match dtype {
67            Int8 => Int8Chunked::from_chunks(name, chunks).into_series(),
68            Int16 => Int16Chunked::from_chunks(name, chunks).into_series(),
69            Int32 => Int32Chunked::from_chunks(name, chunks).into_series(),
70            Int64 => Int64Chunked::from_chunks(name, chunks).into_series(),
71            UInt8 => UInt8Chunked::from_chunks(name, chunks).into_series(),
72            UInt16 => UInt16Chunked::from_chunks(name, chunks).into_series(),
73            UInt32 => UInt32Chunked::from_chunks(name, chunks).into_series(),
74            UInt64 => UInt64Chunked::from_chunks(name, chunks).into_series(),
75            #[cfg(feature = "dtype-i128")]
76            Int128 => Int128Chunked::from_chunks(name, chunks).into_series(),
77            #[cfg(feature = "dtype-u128")]
78            UInt128 => UInt128Chunked::from_chunks(name, chunks).into_series(),
79            #[cfg(feature = "dtype-date")]
80            Date => Int32Chunked::from_chunks(name, chunks)
81                .into_date()
82                .into_series(),
83            #[cfg(feature = "dtype-time")]
84            Time => Int64Chunked::from_chunks(name, chunks)
85                .into_time()
86                .into_series(),
87            #[cfg(feature = "dtype-duration")]
88            Duration(tu) => Int64Chunked::from_chunks(name, chunks)
89                .into_duration(*tu)
90                .into_series(),
91            #[cfg(feature = "dtype-datetime")]
92            Datetime(tu, tz) => Int64Chunked::from_chunks(name, chunks)
93                .into_datetime(*tu, tz.clone())
94                .into_series(),
95            #[cfg(feature = "dtype-decimal")]
96            Decimal(precision, scale) => Int128Chunked::from_chunks(name, chunks)
97                .into_decimal_unchecked(*precision, *scale)
98                .into_series(),
99            #[cfg(feature = "dtype-array")]
100            Array(_, _) => {
101                ArrayChunked::from_chunks_and_dtype_unchecked(name, chunks, dtype.clone())
102                    .into_series()
103            },
104            List(_) => ListChunked::from_chunks_and_dtype_unchecked(name, chunks, dtype.clone())
105                .into_series(),
106            String => StringChunked::from_chunks(name, chunks).into_series(),
107            Binary => BinaryChunked::from_chunks(name, chunks).into_series(),
108            #[cfg(feature = "dtype-categorical")]
109            dt @ (Categorical(_, _) | Enum(_, _)) => {
110                with_match_categorical_physical_type!(dt.cat_physical().unwrap(), |$C| {
111                    let phys = ChunkedArray::from_chunks(name, chunks);
112                    CategoricalChunked::<$C>::from_cats_and_dtype_unchecked(phys, dt.clone()).into_series()
113                })
114            },
115            Boolean => BooleanChunked::from_chunks(name, chunks).into_series(),
116            #[cfg(feature = "dtype-f16")]
117            Float16 => Float16Chunked::from_chunks(name, chunks).into_series(),
118            Float32 => Float32Chunked::from_chunks(name, chunks).into_series(),
119            Float64 => Float64Chunked::from_chunks(name, chunks).into_series(),
120            BinaryOffset => BinaryOffsetChunked::from_chunks(name, chunks).into_series(),
121            #[cfg(feature = "dtype-extension")]
122            Extension(typ, storage) => ExtensionChunked::from_storage(
123                typ.clone(),
124                Series::from_chunks_and_dtype_unchecked(name, chunks, storage),
125            )
126            .into_series(),
127            #[cfg(feature = "dtype-struct")]
128            Struct(_) => {
129                let mut ca =
130                    StructChunked::from_chunks_and_dtype_unchecked(name, chunks, dtype.clone());
131                StructChunked::propagate_nulls_mut(&mut ca);
132                ca.into_series()
133            },
134            #[cfg(feature = "object")]
135            Object(_) => {
136                if let Some(arr) = chunks[0].as_any().downcast_ref::<FixedSizeBinaryArray>() {
137                    assert_eq!(chunks.len(), 1);
138                    // SAFETY:
139                    // this is highly unsafe. it will dereference a raw ptr on the heap
140                    // make sure the ptr is allocated and from this pid
141                    // (the pid is checked before dereference)
142                    {
143                        let pe = PolarsExtension::new(arr.clone());
144                        let s = pe.get_series(&name);
145                        pe.take_and_forget();
146                        s
147                    }
148                } else {
149                    unsafe { get_object_builder(name, 0).from_chunks(chunks) }
150                }
151            },
152            Null => new_null(name, &chunks),
153            Unknown(_) => {
154                panic!("dtype is unknown; consider supplying data-types for all operations")
155            },
156            #[allow(unreachable_patterns)]
157            _ => unreachable!(),
158        }
159    }
160
161    /// # Safety
162    /// The caller must ensure that the given `dtype` matches all the `ArrayRef` dtypes.
163    pub unsafe fn _try_from_arrow_unchecked(
164        name: PlSmallStr,
165        chunks: Vec<ArrayRef>,
166        dtype: &ArrowDataType,
167    ) -> PolarsResult<Self> {
168        Self::_try_from_arrow_unchecked_with_md(name, chunks, dtype, None)
169    }
170
171    /// Create a new Series without checking if the inner dtype of the chunks is correct
172    ///
173    /// # Safety
174    /// The caller must ensure that the given `dtype` matches all the `ArrayRef` dtypes.
175    pub unsafe fn _try_from_arrow_unchecked_with_md(
176        name: PlSmallStr,
177        mut chunks: Vec<ArrayRef>,
178        dtype: &ArrowDataType,
179        md: Option<&Metadata>,
180    ) -> PolarsResult<Self> {
181        match dtype {
182            ArrowDataType::Utf8View => Ok(StringChunked::from_chunks(name, chunks).into_series()),
183            ArrowDataType::Utf8 | ArrowDataType::LargeUtf8 => {
184                let chunks =
185                    cast_chunks(&chunks, &DataType::String, CastOptions::NonStrict).unwrap();
186                Ok(StringChunked::from_chunks(name, chunks).into_series())
187            },
188            ArrowDataType::BinaryView => Ok(BinaryChunked::from_chunks(name, chunks).into_series()),
189            ArrowDataType::LargeBinary => {
190                if let Some(md) = md {
191                    if md.maintain_type() {
192                        return Ok(BinaryOffsetChunked::from_chunks(name, chunks).into_series());
193                    }
194                }
195                let chunks =
196                    cast_chunks(&chunks, &DataType::Binary, CastOptions::NonStrict).unwrap();
197                Ok(BinaryChunked::from_chunks(name, chunks).into_series())
198            },
199            ArrowDataType::Binary => {
200                let chunks =
201                    cast_chunks(&chunks, &DataType::Binary, CastOptions::NonStrict).unwrap();
202                Ok(BinaryChunked::from_chunks(name, chunks).into_series())
203            },
204            ArrowDataType::List(_) | ArrowDataType::LargeList(_) => {
205                let (chunks, dtype) = to_physical_and_dtype(chunks, md);
206                unsafe {
207                    Ok(
208                        ListChunked::from_chunks_and_dtype_unchecked(name, chunks, dtype)
209                            .into_series(),
210                    )
211                }
212            },
213            #[cfg(feature = "dtype-array")]
214            ArrowDataType::FixedSizeList(_, _) => {
215                let (chunks, dtype) = to_physical_and_dtype(chunks, md);
216                unsafe {
217                    Ok(
218                        ArrayChunked::from_chunks_and_dtype_unchecked(name, chunks, dtype)
219                            .into_series(),
220                    )
221                }
222            },
223            ArrowDataType::Boolean => Ok(BooleanChunked::from_chunks(name, chunks).into_series()),
224            #[cfg(feature = "dtype-u8")]
225            ArrowDataType::UInt8 => Ok(UInt8Chunked::from_chunks(name, chunks).into_series()),
226            #[cfg(feature = "dtype-u16")]
227            ArrowDataType::UInt16 => Ok(UInt16Chunked::from_chunks(name, chunks).into_series()),
228            ArrowDataType::UInt32 => Ok(UInt32Chunked::from_chunks(name, chunks).into_series()),
229            ArrowDataType::UInt64 => Ok(UInt64Chunked::from_chunks(name, chunks).into_series()),
230            ArrowDataType::UInt128 => feature_gated!(
231                "dtype-u128",
232                Ok(UInt128Chunked::from_chunks(name, chunks).into_series())
233            ),
234            #[cfg(feature = "dtype-i8")]
235            ArrowDataType::Int8 => Ok(Int8Chunked::from_chunks(name, chunks).into_series()),
236            #[cfg(feature = "dtype-i16")]
237            ArrowDataType::Int16 => Ok(Int16Chunked::from_chunks(name, chunks).into_series()),
238            ArrowDataType::Int32 => Ok(Int32Chunked::from_chunks(name, chunks).into_series()),
239            ArrowDataType::Int64 => Ok(Int64Chunked::from_chunks(name, chunks).into_series()),
240            ArrowDataType::Int128 => feature_gated!(
241                "dtype-i128",
242                Ok(Int128Chunked::from_chunks(name, chunks).into_series())
243            ),
244            #[cfg(feature = "dtype-f16")]
245            ArrowDataType::Float16 => {
246                let chunks =
247                    cast_chunks(&chunks, &DataType::Float16, CastOptions::NonStrict).unwrap();
248                Ok(Float16Chunked::from_chunks(name, chunks).into_series())
249            },
250            ArrowDataType::Float32 => Ok(Float32Chunked::from_chunks(name, chunks).into_series()),
251            ArrowDataType::Float64 => Ok(Float64Chunked::from_chunks(name, chunks).into_series()),
252            #[cfg(feature = "dtype-date")]
253            ArrowDataType::Date32 => {
254                let chunks =
255                    cast_chunks(&chunks, &DataType::Int32, CastOptions::Overflowing).unwrap();
256                Ok(Int32Chunked::from_chunks(name, chunks)
257                    .into_date()
258                    .into_series())
259            },
260            #[cfg(feature = "dtype-datetime")]
261            ArrowDataType::Date64 => {
262                let chunks =
263                    cast_chunks(&chunks, &DataType::Int64, CastOptions::Overflowing).unwrap();
264                let ca = Int64Chunked::from_chunks(name, chunks);
265                Ok(ca.into_datetime(TimeUnit::Milliseconds, None).into_series())
266            },
267            #[cfg(feature = "dtype-datetime")]
268            ArrowDataType::Timestamp(tu, tz) => {
269                let tz = TimeZone::opt_try_new(tz.clone())?;
270                let chunks =
271                    cast_chunks(&chunks, &DataType::Int64, CastOptions::NonStrict).unwrap();
272                let s = Int64Chunked::from_chunks(name, chunks)
273                    .into_datetime(tu.into(), tz)
274                    .into_series();
275                Ok(match tu {
276                    ArrowTimeUnit::Second => &s * MILLISECONDS,
277                    ArrowTimeUnit::Millisecond => s,
278                    ArrowTimeUnit::Microsecond => s,
279                    ArrowTimeUnit::Nanosecond => s,
280                })
281            },
282            #[cfg(feature = "dtype-duration")]
283            ArrowDataType::Duration(tu) => {
284                let chunks =
285                    cast_chunks(&chunks, &DataType::Int64, CastOptions::NonStrict).unwrap();
286                let s = Int64Chunked::from_chunks(name, chunks)
287                    .into_duration(tu.into())
288                    .into_series();
289                Ok(match tu {
290                    ArrowTimeUnit::Second => &s * MILLISECONDS,
291                    ArrowTimeUnit::Millisecond => s,
292                    ArrowTimeUnit::Microsecond => s,
293                    ArrowTimeUnit::Nanosecond => s,
294                })
295            },
296            #[cfg(feature = "dtype-time")]
297            ArrowDataType::Time64(tu) | ArrowDataType::Time32(tu) => {
298                let mut chunks = chunks;
299                if matches!(dtype, ArrowDataType::Time32(_)) {
300                    chunks =
301                        cast_chunks(&chunks, &DataType::Int32, CastOptions::NonStrict).unwrap();
302                }
303                let chunks =
304                    cast_chunks(&chunks, &DataType::Int64, CastOptions::NonStrict).unwrap();
305                let s = Int64Chunked::from_chunks(name, chunks)
306                    .into_time()
307                    .into_series();
308                Ok(match tu {
309                    ArrowTimeUnit::Second => &s * NANOSECONDS,
310                    ArrowTimeUnit::Millisecond => &s * 1_000_000,
311                    ArrowTimeUnit::Microsecond => &s * 1_000,
312                    ArrowTimeUnit::Nanosecond => s,
313                })
314            },
315            ArrowDataType::Decimal32(precision, scale) => {
316                feature_gated!("dtype-decimal", {
317                    polars_compute::decimal::dec128_verify_prec_scale(*precision, *scale)?;
318
319                    let mut chunks = chunks;
320                    for chunk in chunks.iter_mut() {
321                        let old_chunk = chunk
322                            .as_any_mut()
323                            .downcast_mut::<PrimitiveArray<i32>>()
324                            .unwrap();
325
326                        // For now, we just cast the whole data to i128.
327                        let (_, values, validity) = std::mem::take(old_chunk).into_inner();
328                        *chunk = PrimitiveArray::new(
329                            ArrowDataType::Int128,
330                            values.iter().map(|&v| v as i128).collect(),
331                            validity,
332                        )
333                        .to_boxed();
334                    }
335
336                    let s = Int128Chunked::from_chunks(name, chunks)
337                        .into_decimal_unchecked(*precision, *scale)
338                        .into_series();
339                    Ok(s)
340                })
341            },
342            ArrowDataType::Decimal64(precision, scale) => {
343                feature_gated!("dtype-decimal", {
344                    polars_compute::decimal::dec128_verify_prec_scale(*precision, *scale)?;
345
346                    let mut chunks = chunks;
347                    for chunk in chunks.iter_mut() {
348                        let old_chunk = chunk
349                            .as_any_mut()
350                            .downcast_mut::<PrimitiveArray<i64>>()
351                            .unwrap();
352
353                        // For now, we just cast the whole data to i128.
354                        let (_, values, validity) = std::mem::take(old_chunk).into_inner();
355                        *chunk = PrimitiveArray::new(
356                            ArrowDataType::Int128,
357                            values.iter().map(|&v| v as i128).collect(),
358                            validity,
359                        )
360                        .to_boxed();
361                    }
362
363                    let s = Int128Chunked::from_chunks(name, chunks)
364                        .into_decimal_unchecked(*precision, *scale)
365                        .into_series();
366                    Ok(s)
367                })
368            },
369            ArrowDataType::Decimal(precision, scale) => {
370                feature_gated!("dtype-decimal", {
371                    polars_compute::decimal::dec128_verify_prec_scale(*precision, *scale)?;
372
373                    let mut chunks = chunks;
374                    for chunk in chunks.iter_mut() {
375                        *chunk = std::mem::take(
376                            chunk
377                                .as_any_mut()
378                                .downcast_mut::<PrimitiveArray<i128>>()
379                                .unwrap(),
380                        )
381                        .to(ArrowDataType::Int128)
382                        .to_boxed();
383                    }
384
385                    let s = Int128Chunked::from_chunks(name, chunks)
386                        .into_decimal_unchecked(*precision, *scale)
387                        .into_series();
388                    Ok(s)
389                })
390            },
391            ArrowDataType::Decimal256(precision, scale) => {
392                feature_gated!("dtype-decimal", {
393                    use arrow::types::i256;
394
395                    polars_compute::decimal::dec128_verify_prec_scale(*precision, *scale)?;
396
397                    let mut chunks = chunks;
398                    for chunk in chunks.iter_mut() {
399                        let arr = std::mem::take(
400                            chunk
401                                .as_any_mut()
402                                .downcast_mut::<PrimitiveArray<i256>>()
403                                .unwrap(),
404                        );
405                        let arr_128: PrimitiveArray<i128> = arr.iter().map(|opt_v| {
406                            if let Some(v) = opt_v {
407                                let smaller: Option<i128> = (*v).try_into().ok();
408                                let smaller = smaller.filter(|v| dec128_fits(*v, *precision));
409                                smaller.ok_or_else(|| {
410                                    polars_err!(ComputeError: "Decimal256 to Decimal128 conversion overflowed, Decimal256 is not (yet) supported in Polars")
411                                }).map(Some)
412                            } else {
413                                Ok(None)
414                            }
415                        }).try_collect_arr_trusted()?;
416
417                        *chunk = arr_128.to(ArrowDataType::Int128).to_boxed();
418                    }
419
420                    let s = Int128Chunked::from_chunks(name, chunks)
421                        .into_decimal_unchecked(*precision, *scale)
422                        .into_series();
423                    Ok(s)
424                })
425            },
426            ArrowDataType::Null => Ok(new_null(name, &chunks)),
427            #[cfg(not(feature = "dtype-categorical"))]
428            ArrowDataType::Dictionary(_, _, _) => {
429                panic!("activate dtype-categorical to convert dictionary arrays")
430            },
431            #[cfg(feature = "dtype-categorical")]
432            ArrowDataType::Dictionary(key_type, _, _) => {
433                let polars_dtype = DataType::from_arrow(chunks[0].dtype(), md);
434
435                let mut series_iter = chunks.into_iter().map(|arr| {
436                    import_arrow_dictionary_array(name.clone(), arr, key_type, &polars_dtype)
437                });
438
439                let mut first = series_iter.next().unwrap()?;
440
441                for s in series_iter {
442                    first.append_owned(s?)?;
443                }
444
445                Ok(first)
446            },
447            #[cfg(feature = "object")]
448            ArrowDataType::Extension(ext)
449                if ext.name == POLARS_OBJECT_EXTENSION_NAME && ext.metadata.is_some() =>
450            {
451                assert_eq!(chunks.len(), 1);
452                let arr = chunks[0]
453                    .as_any()
454                    .downcast_ref::<FixedSizeBinaryArray>()
455                    .unwrap();
456                // SAFETY:
457                // this is highly unsafe. it will dereference a raw ptr on the heap
458                // make sure the ptr is allocated and from this pid
459                // (the pid is checked before dereference)
460                let s = {
461                    let pe = PolarsExtension::new(arr.clone());
462                    let s = pe.get_series(&name);
463                    pe.take_and_forget();
464                    s
465                };
466                Ok(s)
467            },
468            #[cfg(feature = "dtype-extension")]
469            ArrowDataType::Extension(ext) => {
470                use crate::datatypes::extension::get_extension_type_or_storage;
471
472                for chunk in &mut chunks {
473                    debug_assert!(
474                        chunk.dtype() == dtype,
475                        "expected chunk dtype to be {:?}, got {:?}",
476                        dtype,
477                        chunk.dtype()
478                    );
479                    *chunk.dtype_mut() = ext.inner.clone();
480                }
481                let storage = Series::_try_from_arrow_unchecked_with_md(
482                    name.clone(),
483                    chunks,
484                    &ext.inner,
485                    md,
486                )?;
487
488                Ok(
489                    match get_extension_type_or_storage(
490                        &ext.name,
491                        storage.dtype(),
492                        ext.metadata.as_deref(),
493                    ) {
494                        Some(typ) => ExtensionChunked::from_storage(typ, storage).into_series(),
495                        None => storage,
496                    },
497                )
498            },
499
500            #[cfg(feature = "dtype-struct")]
501            ArrowDataType::Struct(_) => {
502                let (chunks, dtype) = to_physical_and_dtype(chunks, md);
503
504                unsafe {
505                    let mut ca =
506                        StructChunked::from_chunks_and_dtype_unchecked(name, chunks, dtype);
507                    StructChunked::propagate_nulls_mut(&mut ca);
508                    Ok(ca.into_series())
509                }
510            },
511            ArrowDataType::FixedSizeBinary(_) => {
512                let chunks = cast_chunks(&chunks, &DataType::Binary, CastOptions::NonStrict)?;
513                Ok(BinaryChunked::from_chunks(name, chunks).into_series())
514            },
515            ArrowDataType::Map(field, _is_ordered) => {
516                let struct_arrays = chunks
517                    .iter()
518                    .map(|arr| {
519                        let arr = arr.as_any().downcast_ref::<MapArray>().unwrap();
520                        arr.field().clone()
521                    })
522                    .collect::<Vec<_>>();
523
524                let (phys_struct_arrays, dtype) =
525                    to_physical_and_dtype(struct_arrays, field.metadata.as_deref());
526
527                let chunks = chunks
528                    .iter()
529                    .zip(phys_struct_arrays)
530                    .map(|(arr, values)| {
531                        let arr = arr.as_any().downcast_ref::<MapArray>().unwrap();
532                        let offsets: &OffsetsBuffer<i32> = arr.offsets();
533
534                        let validity = arr.validity().cloned();
535
536                        Box::from(ListArray::<i64>::new(
537                            ListArray::<i64>::default_datatype(values.dtype().clone()),
538                            OffsetsBuffer::<i64>::from(offsets),
539                            values,
540                            validity,
541                        )) as ArrayRef
542                    })
543                    .collect();
544
545                unsafe {
546                    let out = ListChunked::from_chunks_and_dtype_unchecked(
547                        name,
548                        chunks,
549                        DataType::List(Box::new(dtype)),
550                    );
551
552                    Ok(out.into_series())
553                }
554            },
555            ArrowDataType::Interval(IntervalUnit::MonthDayNano) => {
556                check_allow_importing_interval_as_struct("month_day_nano_interval")?;
557
558                feature_gated!("dtype-struct", {
559                    let chunks = chunks
560                        .into_iter()
561                        .map(convert_month_day_nano_to_struct)
562                        .collect::<PolarsResult<Vec<_>>>()?;
563
564                    Ok(StructChunked::from_chunks_and_dtype_unchecked(
565                        name,
566                        chunks,
567                        DataType::_month_days_ns_struct_type(),
568                    )
569                    .into_series())
570                })
571            },
572
573            dt => polars_bail!(ComputeError: "cannot create series from {:?}", dt),
574        }
575    }
576
577    #[cfg(feature = "dtype-categorical")]
578    pub fn from_cats_and_dtype(
579        cats: &Series,
580        dtype: &DataType,
581        strict: bool,
582    ) -> PolarsResult<Series> {
583        use std::borrow::Cow;
584
585        let phys = dtype.cat_physical()?;
586        let phys_dtype = DataType::from(phys);
587
588        let mut casted = Cow::Borrowed(cats);
589        if cats.dtype() != &phys_dtype {
590            casted = Cow::Owned(cats.cast(&phys_dtype)?);
591        }
592
593        let out = with_match_categorical_physical_type!(phys, |$C| {
594            // SAFETY: we are guarded by the type system.
595            type PhysCa = ChunkedArray<<$C as PolarsCategoricalType>::PolarsPhysical>;
596            let ca: &PhysCa = casted.as_ref().as_ref().as_ref();
597            CategoricalChunked::<$C>::from_cats_and_dtype(ca.clone(), dtype.clone()).into_series()
598        });
599
600        if strict && out.null_count() != casted.null_count() {
601            polars_bail!(
602                ComputeError:
603                "found invalid category value when converting from physical to {dtype}",
604            );
605        }
606
607        Ok(out)
608    }
609}
610
611fn convert<F: Fn(&dyn Array) -> ArrayRef>(arr: &[ArrayRef], f: F) -> Vec<ArrayRef> {
612    arr.iter().map(|arr| f(&**arr)).collect()
613}
614
615/// Converts to physical types and bubbles up the correct [`DataType`].
616#[allow(clippy::only_used_in_recursion)]
617unsafe fn to_physical_and_dtype(
618    arrays: Vec<ArrayRef>,
619    md: Option<&Metadata>,
620) -> (Vec<ArrayRef>, DataType) {
621    match arrays[0].dtype() {
622        ArrowDataType::Utf8 | ArrowDataType::LargeUtf8 => {
623            let chunks = cast_chunks(&arrays, &DataType::String, CastOptions::NonStrict).unwrap();
624            (chunks, DataType::String)
625        },
626        ArrowDataType::Binary | ArrowDataType::LargeBinary | ArrowDataType::FixedSizeBinary(_) => {
627            let chunks = cast_chunks(&arrays, &DataType::Binary, CastOptions::NonStrict).unwrap();
628            (chunks, DataType::Binary)
629        },
630        #[allow(unused_variables)]
631        dt @ ArrowDataType::Dictionary(_, _, _) => {
632            feature_gated!("dtype-categorical", {
633                let s = unsafe {
634                    let dt = dt.clone();
635                    Series::_try_from_arrow_unchecked_with_md(PlSmallStr::EMPTY, arrays, &dt, md)
636                }
637                .unwrap();
638                (s.chunks().clone(), s.dtype().clone())
639            })
640        },
641        dt @ ArrowDataType::Extension(_) => {
642            feature_gated!("dtype-extension", {
643                let s = unsafe {
644                    let dt = dt.clone();
645                    Series::_try_from_arrow_unchecked_with_md(PlSmallStr::EMPTY, arrays, &dt, md)
646                }
647                .unwrap();
648                (s.chunks().clone(), s.dtype().clone())
649            })
650        },
651        ArrowDataType::List(field) => {
652            let out = convert(&arrays, |arr| {
653                cast(arr, &ArrowDataType::LargeList(field.clone())).unwrap()
654            });
655            to_physical_and_dtype(out, md)
656        },
657        #[cfg(feature = "dtype-array")]
658        ArrowDataType::FixedSizeList(field, size) => {
659            let values = arrays
660                .iter()
661                .map(|arr| {
662                    let arr = arr.as_any().downcast_ref::<FixedSizeListArray>().unwrap();
663                    arr.values().clone()
664                })
665                .collect::<Vec<_>>();
666
667            let (converted_values, dtype) =
668                to_physical_and_dtype(values, field.metadata.as_deref());
669
670            let arrays = arrays
671                .iter()
672                .zip(converted_values)
673                .map(|(arr, values)| {
674                    let arr = arr.as_any().downcast_ref::<FixedSizeListArray>().unwrap();
675
676                    let dtype = FixedSizeListArray::default_datatype(values.dtype().clone(), *size);
677                    Box::from(FixedSizeListArray::new(
678                        dtype,
679                        arr.len(),
680                        values,
681                        arr.validity().cloned(),
682                    )) as ArrayRef
683                })
684                .collect();
685            (arrays, DataType::Array(Box::new(dtype), *size))
686        },
687        ArrowDataType::LargeList(field) => {
688            let values = arrays
689                .iter()
690                .map(|arr| {
691                    let arr = arr.as_any().downcast_ref::<ListArray<i64>>().unwrap();
692                    arr.values().clone()
693                })
694                .collect::<Vec<_>>();
695
696            let (converted_values, dtype) =
697                to_physical_and_dtype(values, field.metadata.as_deref());
698
699            let arrays = arrays
700                .iter()
701                .zip(converted_values)
702                .map(|(arr, values)| {
703                    let arr = arr.as_any().downcast_ref::<ListArray<i64>>().unwrap();
704
705                    let dtype = ListArray::<i64>::default_datatype(values.dtype().clone());
706                    Box::from(ListArray::<i64>::new(
707                        dtype,
708                        arr.offsets().clone(),
709                        values,
710                        arr.validity().cloned(),
711                    )) as ArrayRef
712                })
713                .collect();
714            (arrays, DataType::List(Box::new(dtype)))
715        },
716        ArrowDataType::Struct(_fields) => {
717            feature_gated!("dtype-struct", {
718                let mut pl_fields = None;
719                let arrays = arrays
720                    .iter()
721                    .map(|arr| {
722                        let arr = arr.as_any().downcast_ref::<StructArray>().unwrap();
723                        let (values, dtypes): (Vec<_>, Vec<_>) = arr
724                            .values()
725                            .iter()
726                            .zip(_fields.iter())
727                            .map(|(value, field)| {
728                                let mut out = to_physical_and_dtype(
729                                    vec![value.clone()],
730                                    field.metadata.as_deref(),
731                                );
732                                (out.0.pop().unwrap(), out.1)
733                            })
734                            .unzip();
735
736                        let arrow_fields = values
737                            .iter()
738                            .zip(_fields.iter())
739                            .map(|(arr, field)| {
740                                ArrowField::new(field.name.clone(), arr.dtype().clone(), true)
741                            })
742                            .collect();
743                        let arrow_array = Box::new(StructArray::new(
744                            ArrowDataType::Struct(arrow_fields),
745                            arr.len(),
746                            values,
747                            arr.validity().cloned(),
748                        )) as ArrayRef;
749
750                        if pl_fields.is_none() {
751                            pl_fields = Some(
752                                _fields
753                                    .iter()
754                                    .zip(dtypes)
755                                    .map(|(field, dtype)| Field::new(field.name.clone(), dtype))
756                                    .collect_vec(),
757                            )
758                        }
759
760                        arrow_array
761                    })
762                    .collect_vec();
763
764                (arrays, DataType::Struct(pl_fields.unwrap()))
765            })
766        },
767        // Use Series architecture to convert nested logical types to physical.
768        dt @ (ArrowDataType::Duration(_)
769        | ArrowDataType::Time32(_)
770        | ArrowDataType::Time64(_)
771        | ArrowDataType::Timestamp(_, _)
772        | ArrowDataType::Date32
773        | ArrowDataType::Decimal(_, _)
774        | ArrowDataType::Date64
775        | ArrowDataType::Map(_, _)) => {
776            let dt = dt.clone();
777            let mut s = Series::_try_from_arrow_unchecked(PlSmallStr::EMPTY, arrays, &dt).unwrap();
778            let dtype = s.dtype().clone();
779            (std::mem::take(s.chunks_mut()), dtype)
780        },
781        dt => {
782            let dtype = DataType::from_arrow(dt, md);
783            (arrays, dtype)
784        },
785    }
786}
787
788#[cfg(feature = "dtype-categorical")]
789unsafe fn import_arrow_dictionary_array(
790    name: PlSmallStr,
791    arr: Box<dyn Array>,
792    key_type: &arrow::datatypes::IntegerType,
793    polars_dtype: &DataType,
794) -> PolarsResult<Series> {
795    use arrow::datatypes::IntegerType as I;
796
797    if matches!(
798        polars_dtype,
799        DataType::Categorical(_, _) | DataType::Enum(_, _)
800    ) {
801        macro_rules! unpack_categorical_chunked {
802            ($dt:ty) => {{
803                let arr = arr.as_any().downcast_ref::<DictionaryArray<$dt>>().unwrap();
804                let keys = arr.keys();
805                let values = arr.values();
806                let values = cast(&**values, &ArrowDataType::Utf8View)?;
807                let values = values.as_any().downcast_ref::<Utf8ViewArray>().unwrap();
808                with_match_categorical_physical_type!(polars_dtype.cat_physical().unwrap(), |$C| {
809                    let ca = CategoricalChunked::<$C>::from_str_iter(
810                        name,
811                        polars_dtype.clone(),
812                        keys.iter().map(|k| {
813                            let k: usize = (*k?).try_into().ok()?;
814                            values.get(k)
815                        }),
816                    )?;
817                    Ok(ca.into_series())
818                })
819            }};
820        }
821
822        match key_type {
823            I::Int8 => unpack_categorical_chunked!(i8),
824            I::UInt8 => unpack_categorical_chunked!(u8),
825            I::Int16 => unpack_categorical_chunked!(i16),
826            I::UInt16 => unpack_categorical_chunked!(u16),
827            I::Int32 => unpack_categorical_chunked!(i32),
828            I::UInt32 => unpack_categorical_chunked!(u32),
829            I::Int64 => unpack_categorical_chunked!(i64),
830            I::UInt64 => unpack_categorical_chunked!(u64),
831            _ => polars_bail!(
832                ComputeError: "unsupported arrow key type: {key_type:?}"
833            ),
834        }
835    } else {
836        macro_rules! unpack_keys_values {
837            ($dt:ty) => {{
838                let arr = arr.as_any().downcast_ref::<DictionaryArray<$dt>>().unwrap();
839                let keys = arr.keys();
840                let keys = polars_compute::cast::primitive_to_primitive::<
841                    $dt,
842                    <IdxType as PolarsNumericType>::Native,
843                >(keys, &IDX_DTYPE.to_arrow(CompatLevel::newest()));
844                (keys, arr.values())
845            }};
846        }
847
848        let (keys, values) = match key_type {
849            I::Int8 => unpack_keys_values!(i8),
850            I::UInt8 => unpack_keys_values!(u8),
851            I::Int16 => unpack_keys_values!(i16),
852            I::UInt16 => unpack_keys_values!(u16),
853            I::Int32 => unpack_keys_values!(i32),
854            I::UInt32 => unpack_keys_values!(u32),
855            I::Int64 => unpack_keys_values!(i64),
856            I::UInt64 => unpack_keys_values!(u64),
857            _ => polars_bail!(
858                ComputeError: "unsupported arrow key type: {key_type:?}"
859            ),
860        };
861
862        let values = Series::_try_from_arrow_unchecked_with_md(
863            name,
864            vec![values.clone()],
865            values.dtype(),
866            None,
867        )?;
868
869        values.take(&IdxCa::from_chunks_and_dtype(
870            PlSmallStr::EMPTY,
871            vec![keys.to_boxed()],
872            IDX_DTYPE,
873        ))
874    }
875}
876
877#[cfg(feature = "dtype-struct")]
878fn convert_month_day_nano_to_struct(chunk: Box<dyn Array>) -> PolarsResult<Box<dyn Array>> {
879    let arr: &PrimitiveArray<months_days_ns> = chunk.as_any().downcast_ref().unwrap();
880
881    let values: &[months_days_ns] = arr.values();
882
883    let (months_out, days_out, nanoseconds_out): (Vec<i32>, Vec<i32>, Vec<i64>) = values
884        .iter()
885        .map(|x| (x.months(), x.days(), x.ns()))
886        .collect();
887
888    let out = StructArray::new(
889        DataType::_month_days_ns_struct_type()
890            .to_physical()
891            .to_arrow(CompatLevel::newest()),
892        arr.len(),
893        vec![
894            PrimitiveArray::<i32>::from_vec(months_out).boxed(),
895            PrimitiveArray::<i32>::from_vec(days_out).boxed(),
896            PrimitiveArray::<i64>::from_vec(nanoseconds_out).boxed(),
897        ],
898        arr.validity().cloned(),
899    );
900
901    Ok(out.boxed())
902}
903
904fn check_types(chunks: &[ArrayRef]) -> PolarsResult<ArrowDataType> {
905    let mut chunks_iter = chunks.iter();
906    let dtype: ArrowDataType = chunks_iter
907        .next()
908        .ok_or_else(|| polars_err!(NoData: "expected at least one array-ref"))?
909        .dtype()
910        .clone();
911
912    for chunk in chunks_iter {
913        if chunk.dtype() != &dtype {
914            polars_bail!(
915                ComputeError: "cannot create series from multiple arrays with different types"
916            );
917        }
918    }
919    Ok(dtype)
920}
921
922impl Series {
923    pub fn try_new<T>(
924        name: PlSmallStr,
925        data: T,
926    ) -> Result<Self, <(PlSmallStr, T) as TryInto<Self>>::Error>
927    where
928        (PlSmallStr, T): TryInto<Self>,
929    {
930        // # TODO
931        // * Remove the TryFrom<tuple> impls in favor of this
932        <(PlSmallStr, T) as TryInto<Self>>::try_into((name, data))
933    }
934}
935
936impl TryFrom<(PlSmallStr, Vec<ArrayRef>)> for Series {
937    type Error = PolarsError;
938
939    fn try_from(name_arr: (PlSmallStr, Vec<ArrayRef>)) -> PolarsResult<Self> {
940        let (name, chunks) = name_arr;
941
942        let dtype = check_types(&chunks)?;
943        // SAFETY:
944        // dtype is checked
945        unsafe { Series::_try_from_arrow_unchecked(name, chunks, &dtype) }
946    }
947}
948
949impl TryFrom<(PlSmallStr, ArrayRef)> for Series {
950    type Error = PolarsError;
951
952    fn try_from(name_arr: (PlSmallStr, ArrayRef)) -> PolarsResult<Self> {
953        let (name, arr) = name_arr;
954        Series::try_from((name, vec![arr]))
955    }
956}
957
958impl TryFrom<(&ArrowField, Vec<ArrayRef>)> for Series {
959    type Error = PolarsError;
960
961    fn try_from(field_arr: (&ArrowField, Vec<ArrayRef>)) -> PolarsResult<Self> {
962        let (field, chunks) = field_arr;
963        let arrow_dt = field.dtype();
964        let dtype = check_types(&chunks)?;
965        let compatible = match (&dtype, arrow_dt) {
966            // See #26174, we don't care about dictionary ordering.
967            (
968                ArrowDataType::Dictionary(int0, inner0, _ord0),
969                ArrowDataType::Dictionary(int1, inner1, _ord1),
970            ) => (int0, inner0) == (int1, inner1),
971            (l, r) => l == r,
972        };
973        polars_ensure!(compatible, ComputeError: "Arrow Field dtype does not match the ArrayRef dtypes");
974
975        // SAFETY:
976        // dtype is checked
977        unsafe {
978            Series::_try_from_arrow_unchecked_with_md(
979                field.name.clone(),
980                chunks,
981                &dtype,
982                field.metadata.as_deref(),
983            )
984        }
985    }
986}
987
988impl TryFrom<(&ArrowField, ArrayRef)> for Series {
989    type Error = PolarsError;
990
991    fn try_from(field_arr: (&ArrowField, ArrayRef)) -> PolarsResult<Self> {
992        let (field, arr) = field_arr;
993        Series::try_from((field, vec![arr]))
994    }
995}
996
997/// Used to convert a [`ChunkedArray`], `&dyn SeriesTrait` and [`Series`]
998/// into a [`Series`].
999/// # Safety
1000///
1001/// This trait is marked `unsafe` as the `is_series` return is used
1002/// to transmute to `Series`. This must always return `false` except
1003/// for `Series` structs.
1004pub unsafe trait IntoSeries {
1005    fn is_series() -> bool {
1006        false
1007    }
1008
1009    fn into_series(self) -> Series
1010    where
1011        Self: Sized;
1012}
1013
1014impl<T> From<ChunkedArray<T>> for Series
1015where
1016    T: PolarsDataType,
1017    ChunkedArray<T>: IntoSeries,
1018{
1019    fn from(ca: ChunkedArray<T>) -> Self {
1020        ca.into_series()
1021    }
1022}
1023
1024#[cfg(feature = "dtype-date")]
1025impl From<DateChunked> for Series {
1026    fn from(a: DateChunked) -> Self {
1027        a.into_series()
1028    }
1029}
1030
1031#[cfg(feature = "dtype-datetime")]
1032impl From<DatetimeChunked> for Series {
1033    fn from(a: DatetimeChunked) -> Self {
1034        a.into_series()
1035    }
1036}
1037
1038#[cfg(feature = "dtype-duration")]
1039impl From<DurationChunked> for Series {
1040    fn from(a: DurationChunked) -> Self {
1041        a.into_series()
1042    }
1043}
1044
1045#[cfg(feature = "dtype-time")]
1046impl From<TimeChunked> for Series {
1047    fn from(a: TimeChunked) -> Self {
1048        a.into_series()
1049    }
1050}
1051
1052unsafe impl IntoSeries for Arc<dyn SeriesTrait> {
1053    fn into_series(self) -> Series {
1054        Series(self)
1055    }
1056}
1057
1058unsafe impl IntoSeries for Series {
1059    fn is_series() -> bool {
1060        true
1061    }
1062
1063    fn into_series(self) -> Series {
1064        self
1065    }
1066}
1067
1068fn new_null(name: PlSmallStr, chunks: &[ArrayRef]) -> Series {
1069    let len = chunks.iter().map(|arr| arr.len()).sum();
1070    Series::new_null(name, len)
1071}