Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/py-polars/tests/unit/operations/test_extend_constant.py
6939 views
1
from __future__ import annotations
2
3
from datetime import date, datetime, time, timedelta
4
from typing import TYPE_CHECKING, Any
5
6
import pytest
7
8
import polars as pl
9
from polars.exceptions import ShapeError
10
from polars.testing import assert_frame_equal, assert_series_equal
11
12
if TYPE_CHECKING:
13
from polars._typing import PolarsDataType
14
15
16
@pytest.mark.parametrize(
17
("const", "dtype"),
18
[
19
(1, pl.Int8),
20
(4, pl.UInt32),
21
(4.5, pl.Float32),
22
(None, pl.Float64),
23
("白鵬翔", pl.String),
24
(date.today(), pl.Date),
25
(datetime.now(), pl.Datetime("ns")),
26
(time(23, 59, 59), pl.Time),
27
(timedelta(hours=7, seconds=123), pl.Duration("ms")),
28
],
29
)
30
def test_extend_constant(const: Any, dtype: PolarsDataType) -> None:
31
df = pl.DataFrame({"a": pl.Series("s", [None], dtype=dtype)})
32
33
expected_df = pl.DataFrame(
34
{"a": pl.Series("s", [None, const, const, const], dtype=dtype)}
35
)
36
37
assert_frame_equal(df.select(pl.col("a").extend_constant(const, 3)), expected_df)
38
39
s = pl.Series("s", [None], dtype=dtype)
40
expected = pl.Series("s", [None, const, const, const], dtype=dtype)
41
assert_series_equal(s.extend_constant(const, 3), expected)
42
43
# test n expr
44
expected = pl.Series("s", [None, const, const], dtype=dtype)
45
assert_series_equal(s.extend_constant(const, pl.lit(2)), expected)
46
47
# test value expr
48
expected = pl.Series("s", [None, const, const, const], dtype=dtype)
49
assert_series_equal(s.extend_constant(pl.lit(const, dtype=dtype), 3), expected)
50
51
52
@pytest.mark.parametrize(
53
("const", "dtype"),
54
[
55
(1, pl.Int8),
56
(4, pl.UInt32),
57
(4.5, pl.Float32),
58
(None, pl.Float64),
59
("白鵬翔", pl.String),
60
(date.today(), pl.Date),
61
(datetime.now(), pl.Datetime("ns")),
62
(time(23, 59, 59), pl.Time),
63
(timedelta(hours=7, seconds=123), pl.Duration("ms")),
64
],
65
)
66
def test_extend_constant_arr(const: Any, dtype: PolarsDataType) -> None:
67
"""
68
Test extend_constant in pl.List array.
69
70
NOTE: This function currently fails when the Series is a list with a single [None]
71
value. Hence, this function does not begin with [[None]], but [[const]].
72
"""
73
s = pl.Series("s", [[const]], dtype=pl.List(dtype))
74
75
expected = pl.Series("s", [[const, const, const, const]], dtype=pl.List(dtype))
76
77
assert_series_equal(s.list.eval(pl.element().extend_constant(const, 3)), expected)
78
79
80
def test_extend_by_not_uint_expr() -> None:
81
s = pl.Series("s", [1])
82
with pytest.raises(ShapeError, match="'value' must be a scalar value"):
83
s.extend_constant(pl.Series([2, 3]), 3)
84
with pytest.raises(ShapeError, match="'n' must be a scalar value"):
85
s.extend_constant(2, pl.Series([3, 4]))
86
87