Path: blob/main/py-polars/tests/unit/interop/numpy/test_from_numpy_series.py
8420 views
from __future__ import annotations12from datetime import timedelta3from typing import TYPE_CHECKING45import numpy as np6import pytest7from numpy.testing import assert_array_equal89import polars as pl1011if TYPE_CHECKING:12from polars._typing import TimeUnit131415@pytest.mark.parametrize("time_unit", ["ms", "us", "ns"])16def test_from_numpy_timedelta(time_unit: TimeUnit) -> None:17s = pl.Series(18"name",19np.array(20[timedelta(days=1), timedelta(seconds=1)], dtype=f"timedelta64[{time_unit}]"21),22)23assert s.dtype == pl.Duration(time_unit)24assert s.name == "name"25assert s.dt[0] == timedelta(days=1)26assert s.dt[1] == timedelta(seconds=1)272829def test_from_numpy_records() -> None:30# numpy arrays in dicts/records31arr_int = np.array([1, 2, 3], dtype=np.int64)32arr_float = np.array([1.1, 2.2, 3.3], dtype=np.float64)33arr_bool = np.array([True, False, True], dtype=np.bool_)3435s = pl.Series(36name="data",37values=[{"ints": arr_int, "floats": arr_float, "bools": arr_bool}],38)39assert s.dtype == pl.Struct(40{41"ints": pl.List(pl.Int64),42"floats": pl.List(pl.Float64),43"bools": pl.List(pl.Boolean),44}45)46round_trip_array = s.to_frame().unnest("data").row(0)47assert_array_equal(48round_trip_array,49[arr_int, arr_float, arr_bool],50)5152data = [53{"id": 1, "values": np.array([1, 2, 3], dtype=np.int64)},54{"id": 2, "values": np.array([4, 5, 6], dtype=np.int64)},55{"id": 3, "values": np.array([7, 8, 9], dtype=np.int64)},56]57s = pl.Series("data", data)58assert s.dtype == pl.Struct({"id": pl.Int64, "values": pl.List(pl.Int64)})59assert len(s) == 3606162@pytest.mark.parametrize(63("numpy_dtype", "polars_dtype"),64[65(np.int8, pl.Int8),66(np.int16, pl.Int16),67(np.int32, pl.Int32),68(np.int64, pl.Int64),69(np.uint8, pl.UInt8),70(np.uint16, pl.UInt16),71(np.uint32, pl.UInt32),72(np.uint64, pl.UInt64),73(np.float16, pl.Float16),74(np.float32, pl.Float32),75(np.float64, pl.Float64),76(np.bool_, pl.Boolean),77],78)79def test_from_numpy_records_2d(80numpy_dtype: type[np.generic], polars_dtype: pl.DataType81) -> None:82arr2d = np.array([[0, 1], [2, 3]], dtype=numpy_dtype)83s = pl.Series("data", [{"id": 1, "values": arr2d}])8485assert s.dtype == pl.Struct(86{"id": pl.Int64, "values": pl.List(pl.Array(polars_dtype, shape=(2,)))}87)88expected_array_values = (89[[False, True], [True, True]]90if polars_dtype == pl.Boolean91else [[0, 1], [2, 3]] # type: ignore[list-item]92)93assert s[0] == {"id": 1, "values": expected_array_values}9495round_trip_array = s.to_numpy()[0][1]96assert_array_equal(round_trip_array, arr2d)979899