Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/py-polars/tests/unit/operations/namespaces/test_name.py
6940 views
1
from __future__ import annotations
2
3
from collections import OrderedDict
4
5
import polars as pl
6
from polars.testing import assert_frame_equal
7
8
9
def test_name_change_case() -> None:
10
df = pl.DataFrame(
11
schema={"ColX": pl.Int32, "ColY": pl.String},
12
).with_columns(
13
pl.all().name.to_uppercase(),
14
pl.all().name.to_lowercase(),
15
)
16
assert df.schema == OrderedDict(
17
[
18
("ColX", pl.Int32),
19
("ColY", pl.String),
20
("COLX", pl.Int32),
21
("COLY", pl.String),
22
("colx", pl.Int32),
23
("coly", pl.String),
24
]
25
)
26
27
28
def test_name_prefix_suffix() -> None:
29
df = pl.DataFrame(
30
schema={"ColX": pl.Int32, "ColY": pl.String},
31
).with_columns(
32
pl.all().name.prefix("#"),
33
pl.all().name.suffix("!!"),
34
)
35
assert df.schema == OrderedDict(
36
[
37
("ColX", pl.Int32),
38
("ColY", pl.String),
39
("#ColX", pl.Int32),
40
("#ColY", pl.String),
41
("ColX!!", pl.Int32),
42
("ColY!!", pl.String),
43
]
44
)
45
46
47
def test_name_update_all() -> None:
48
df = pl.DataFrame(
49
schema={
50
"col1": pl.UInt32,
51
"col2": pl.Float64,
52
"other": pl.UInt64,
53
}
54
)
55
assert (
56
df.select(
57
pl.col("col2").append(pl.col("other")),
58
pl.col("col1").append(pl.col("other")).name.keep(),
59
pl.col("col1").append(pl.col("other")).name.prefix("prefix_"),
60
pl.col("col1").append(pl.col("other")).name.suffix("_suffix"),
61
)
62
).schema == OrderedDict(
63
[
64
("col2", pl.Float64),
65
("col1", pl.UInt64),
66
("prefix_col1", pl.UInt64),
67
("col1_suffix", pl.UInt64),
68
]
69
)
70
71
72
def test_name_map_chain_21164() -> None:
73
df = pl.DataFrame({"MyCol": [0, 1, 2]})
74
assert_frame_equal(
75
df.select(pl.all().name.to_lowercase().name.suffix("_suffix")),
76
df.select(mycol_suffix=pl.col("MyCol")),
77
)
78
79
80
def test_when_then_keep_map_13858() -> None:
81
df = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
82
83
assert_frame_equal(
84
df.with_columns(
85
pl.when(True)
86
.then(pl.int_range(3))
87
.otherwise(pl.all())
88
.name.keep()
89
.name.suffix("_other")
90
),
91
df.with_columns(a_other=pl.int_range(3), b_other=pl.int_range(3)),
92
)
93
94
95
def test_keep_name_struct_field_23669() -> None:
96
df = pl.DataFrame(
97
[
98
pl.Series("foo", [{"x": 1}], pl.Struct({"x": pl.Int64})),
99
pl.Series("bar", [{"x": 2}], pl.Struct({"x": pl.Int64})),
100
]
101
)
102
assert_frame_equal(
103
df.select(pl.all().struct.field("x").name.keep()),
104
pl.DataFrame(
105
[
106
pl.Series("foo", [1], pl.Int64),
107
pl.Series("bar", [2], pl.Int64),
108
]
109
),
110
)
111
112