/
struct.py
170 lines (146 loc) · 6.42 KB
/
struct.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
from __future__ import annotations
from typing import TYPE_CHECKING, Sequence
from polars._utils.wrap import wrap_expr
if TYPE_CHECKING:
from polars import Expr
class ExprStructNameSpace:
"""Namespace for struct related expressions."""
_accessor = "struct"
def __init__(self, expr: Expr):
self._pyexpr = expr._pyexpr
def __getitem__(self, item: str | int) -> Expr:
if isinstance(item, str):
return self.field(item)
elif isinstance(item, int):
return wrap_expr(self._pyexpr.struct_field_by_index(item))
else:
msg = f"expected type 'int | str', got {type(item).__name__!r} ({item!r})"
raise TypeError(msg)
def field(self, name: str) -> Expr:
"""
Retrieve a `Struct` field as a new Series.
Parameters
----------
name
Name of the struct field to retrieve.
Examples
--------
>>> df = pl.DataFrame(
... {
... "aaa": [1, 2],
... "bbb": ["ab", "cd"],
... "ccc": [True, None],
... "ddd": [[1, 2], [3]],
... }
... ).select(pl.struct(["aaa", "bbb", "ccc", "ddd"]).alias("struct_col"))
>>> df
shape: (2, 1)
┌──────────────────────┐
│ struct_col │
│ --- │
│ struct[4] │
╞══════════════════════╡
│ {1,"ab",true,[1, 2]} │
│ {2,"cd",null,[3]} │
└──────────────────────┘
Retrieve struct field(s) as Series:
>>> df.select(pl.col("struct_col").struct.field("bbb"))
shape: (2, 1)
┌─────┐
│ bbb │
│ --- │
│ str │
╞═════╡
│ ab │
│ cd │
└─────┘
>>> df.select(
... pl.col("struct_col").struct.field("bbb"),
... pl.col("struct_col").struct.field("ddd"),
... )
shape: (2, 2)
┌─────┬───────────┐
│ bbb ┆ ddd │
│ --- ┆ --- │
│ str ┆ list[i64] │
╞═════╪═══════════╡
│ ab ┆ [1, 2] │
│ cd ┆ [3] │
└─────┴───────────┘
"""
return wrap_expr(self._pyexpr.struct_field_by_name(name))
def rename_fields(self, names: Sequence[str]) -> Expr:
"""
Rename the fields of the struct.
Parameters
----------
names
New names, given in the same order as the struct's fields.
Examples
--------
>>> df = pl.DataFrame(
... {
... "aaa": [1, 2],
... "bbb": ["ab", "cd"],
... "ccc": [True, None],
... "ddd": [[1, 2], [3]],
... }
... ).select(pl.struct(["aaa", "bbb", "ccc", "ddd"]).alias("struct_col"))
>>> df
shape: (2, 1)
┌──────────────────────┐
│ struct_col │
│ --- │
│ struct[4] │
╞══════════════════════╡
│ {1,"ab",true,[1, 2]} │
│ {2,"cd",null,[3]} │
└──────────────────────┘
>>> df.unnest("struct_col")
shape: (2, 4)
┌─────┬─────┬──────┬───────────┐
│ aaa ┆ bbb ┆ ccc ┆ ddd │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ bool ┆ list[i64] │
╞═════╪═════╪══════╪═══════════╡
│ 1 ┆ ab ┆ true ┆ [1, 2] │
│ 2 ┆ cd ┆ null ┆ [3] │
└─────┴─────┴──────┴───────────┘
Rename fields:
>>> df = df.select(
... pl.col("struct_col").struct.rename_fields(["www", "xxx", "yyy", "zzz"])
... )
>>> df.unnest("struct_col")
shape: (2, 4)
┌─────┬─────┬──────┬───────────┐
│ www ┆ xxx ┆ yyy ┆ zzz │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ bool ┆ list[i64] │
╞═════╪═════╪══════╪═══════════╡
│ 1 ┆ ab ┆ true ┆ [1, 2] │
│ 2 ┆ cd ┆ null ┆ [3] │
└─────┴─────┴──────┴───────────┘
Following a rename, the previous field names (obviously) cannot be referenced:
>>> df.select(pl.col("struct_col").struct.field("aaa")) # doctest: +SKIP
StructFieldNotFoundError: aaa
"""
return wrap_expr(self._pyexpr.struct_rename_fields(names))
def json_encode(self) -> Expr:
"""
Convert this struct to a string column with json values.
Examples
--------
>>> pl.DataFrame(
... {"a": [{"a": [1, 2], "b": [45]}, {"a": [9, 1, 3], "b": None}]}
... ).with_columns(pl.col("a").struct.json_encode().alias("encoded"))
shape: (2, 2)
┌──────────────────┬────────────────────────┐
│ a ┆ encoded │
│ --- ┆ --- │
│ struct[2] ┆ str │
╞══════════════════╪════════════════════════╡
│ {[1, 2],[45]} ┆ {"a":[1,2],"b":[45]} │
│ {[9, 1, 3],null} ┆ {"a":[9,1,3],"b":null} │
└──────────────────┴────────────────────────┘
"""
return wrap_expr(self._pyexpr.struct_json_encode())