/
array.py
623 lines (527 loc) · 14.8 KB
/
array.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
from __future__ import annotations
from typing import TYPE_CHECKING, Callable, Sequence
from polars import functions as F
from polars._utils.wrap import wrap_s
from polars.series.utils import expr_dispatch
if TYPE_CHECKING:
from datetime import date, datetime, time
from polars import Series
from polars.polars import PySeries
from polars.type_aliases import IntoExpr, IntoExprColumn
@expr_dispatch
class ArrayNameSpace:
"""Namespace for list related methods."""
_accessor = "arr"
def __init__(self, series: Series):
self._s: PySeries = series._s
def min(self) -> Series:
"""
Compute the min values of the sub-arrays.
Examples
--------
>>> s = pl.Series("a", [[1, 2], [4, 3]], dtype=pl.Array(pl.Int64, 2))
>>> s.arr.min()
shape: (2,)
Series: 'a' [i64]
[
1
3
]
"""
def max(self) -> Series:
"""
Compute the max values of the sub-arrays.
Examples
--------
>>> s = pl.Series("a", [[1, 2], [4, 3]], dtype=pl.Array(pl.Int64, 2))
>>> s.arr.max()
shape: (2,)
Series: 'a' [i64]
[
2
4
]
"""
def sum(self) -> Series:
"""
Compute the sum values of the sub-arrays.
Examples
--------
>>> s = pl.Series([[1, 2], [4, 3]], dtype=pl.Array(pl.Int64, 2))
>>> s.arr.sum()
shape: (2,)
Series: '' [i64]
[
3
7
]
"""
def std(self, ddof: int = 1) -> Series:
"""
Compute the std of the values of the sub-arrays.
Examples
--------
>>> s = pl.Series("a", [[1, 2], [4, 3]], dtype=pl.Array(pl.Int64, 2))
>>> s.arr.std()
shape: (2,)
Series: 'a' [f64]
[
0.707107
0.707107
]
"""
def var(self, ddof: int = 1) -> Series:
"""
Compute the var of the values of the sub-arrays.
Examples
--------
>>> s = pl.Series("a", [[1, 2], [4, 3]], dtype=pl.Array(pl.Int64, 2))
>>> s.arr.var()
shape: (2,)
Series: 'a' [f64]
[
0.5
0.5
]
"""
def median(self) -> Series:
"""
Compute the median of the values of the sub-arrays.
Examples
--------
>>> s = pl.Series("a", [[1, 2], [4, 3]], dtype=pl.Array(pl.Int64, 2))
>>> s.arr.median()
shape: (2,)
Series: 'a' [f64]
[
1.5
3.5
]
"""
def unique(self, *, maintain_order: bool = False) -> Series:
"""
Get the unique/distinct values in the array.
Parameters
----------
maintain_order
Maintain order of data. This requires more work.
Returns
-------
Series
Series of data type :class:`List`.
Examples
--------
>>> s = pl.Series([[1, 1, 2], [3, 4, 5]], dtype=pl.Array(pl.Int64, 3))
>>> s.arr.unique()
shape: (2,)
Series: '' [list[i64]]
[
[1, 2]
[3, 4, 5]
]
"""
def n_unique(self) -> Series:
"""
Count the number of unique values in every sub-arrays.
Examples
--------
>>> s = pl.Series("a", [[1, 2], [4, 4]], dtype=pl.Array(pl.Int64, 2))
>>> s.arr.n_unique()
shape: (2,)
Series: 'a' [u32]
[
2
1
]
"""
def to_list(self) -> Series:
"""
Convert an Array column into a List column with the same inner data type.
Returns
-------
Series
Series of data type :class:`List`.
Examples
--------
>>> s = pl.Series([[1, 2], [3, 4]], dtype=pl.Array(pl.Int8, 2))
>>> s.arr.to_list()
shape: (2,)
Series: '' [list[i8]]
[
[1, 2]
[3, 4]
]
"""
def any(self) -> Series:
"""
Evaluate whether any boolean value is true for every subarray.
Returns
-------
Series
Series of data type :class:`Boolean`.
Examples
--------
>>> s = pl.Series(
... [[True, True], [False, True], [False, False], [None, None], None],
... dtype=pl.Array(pl.Boolean, 2),
... )
>>> s.arr.any()
shape: (5,)
Series: '' [bool]
[
true
true
false
false
null
]
"""
def all(self) -> Series:
"""
Evaluate whether all boolean values are true for every subarray.
Returns
-------
Series
Series of data type :class:`Boolean`.
Examples
--------
>>> s = pl.Series(
... [[True, True], [False, True], [False, False], [None, None], None],
... dtype=pl.Array(pl.Boolean, 2),
... )
>>> s.arr.all()
shape: (5,)
Series: '' [bool]
[
true
false
false
true
null
]
"""
def sort(
self,
*,
descending: bool = False,
nulls_last: bool = False,
multithreaded: bool = True,
) -> Series:
"""
Sort the arrays in this column.
Parameters
----------
descending
Sort in descending order.
nulls_last
Place null values last.
multithreaded
Sort using multiple threads.
Examples
--------
>>> s = pl.Series("a", [[3, 2, 1], [9, 1, 2]], dtype=pl.Array(pl.Int64, 3))
>>> s.arr.sort()
shape: (2,)
Series: 'a' [array[i64, 3]]
[
[1, 2, 3]
[1, 2, 9]
]
>>> s.arr.sort(descending=True)
shape: (2,)
Series: 'a' [array[i64, 3]]
[
[3, 2, 1]
[9, 2, 1]
]
"""
def reverse(self) -> Series:
"""
Reverse the arrays in this column.
Examples
--------
>>> s = pl.Series("a", [[3, 2, 1], [9, 1, 2]], dtype=pl.Array(pl.Int64, 3))
>>> s.arr.reverse()
shape: (2,)
Series: 'a' [array[i64, 3]]
[
[1, 2, 3]
[2, 1, 9]
]
"""
def arg_min(self) -> Series:
"""
Retrieve the index of the minimal value in every sub-array.
Returns
-------
Series
Series of data type :class:`UInt32` or :class:`UInt64`
(depending on compilation).
Examples
--------
>>> s = pl.Series("a", [[3, 2, 1], [9, 1, 2]], dtype=pl.Array(pl.Int64, 3))
>>> s.arr.arg_min()
shape: (2,)
Series: 'a' [u32]
[
2
1
]
"""
def arg_max(self) -> Series:
"""
Retrieve the index of the maximum value in every sub-array.
Returns
-------
Series
Series of data type :class:`UInt32` or :class:`UInt64`
(depending on compilation).
Examples
--------
>>> s = pl.Series("a", [[0, 9, 3], [9, 1, 2]], dtype=pl.Array(pl.Int64, 3))
>>> s.arr.arg_max()
shape: (2,)
Series: 'a' [u32]
[
1
0
]
"""
def get(self, index: int | IntoExprColumn, *, null_on_oob: bool = True) -> Series:
"""
Get the value by index in the sub-arrays.
So index `0` would return the first item of every sublist
and index `-1` would return the last item of every sublist
if an index is out of bounds, it will return a `None`.
Parameters
----------
index
Index to return per sublist
null_on_oob
Behavior if an index is out of bounds:
True -> set as null
False -> raise an error
Returns
-------
Series
Series of innter data type.
Examples
--------
>>> s = pl.Series(
... "a", [[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=pl.Array(pl.Int32, 3)
... )
>>> s.arr.get(pl.Series([1, -2, 0]), null_on_oob=True)
shape: (3,)
Series: 'a' [i32]
[
2
5
7
]
"""
def first(self) -> Series:
"""
Get the first value of the sub-arrays.
Examples
--------
>>> s = pl.Series(
... "a", [[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=pl.Array(pl.Int32, 3)
... )
>>> s.arr.first()
shape: (3,)
Series: 'a' [i32]
[
1
4
7
]
"""
def last(self) -> Series:
"""
Get the last value of the sub-arrays.
Examples
--------
>>> s = pl.Series(
... "a", [[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=pl.Array(pl.Int32, 3)
... )
>>> s.arr.last()
shape: (3,)
Series: 'a' [i32]
[
3
6
9
]
"""
def join(self, separator: IntoExprColumn, *, ignore_nulls: bool = True) -> Series:
"""
Join all string items in a sub-array and place a separator between them.
This errors if inner type of array `!= String`.
Parameters
----------
separator
string to separate the items with
ignore_nulls
Ignore null values (default).
If set to ``False``, null values will be propagated.
If the sub-list contains any null values, the output is ``None``.
Returns
-------
Series
Series of data type :class:`String`.
Examples
--------
>>> s = pl.Series([["x", "y"], ["a", "b"]], dtype=pl.Array(pl.String, 2))
>>> s.arr.join(separator="-")
shape: (2,)
Series: '' [str]
[
"x-y"
"a-b"
]
"""
def explode(self) -> Series:
"""
Returns a column with a separate row for every array element.
Returns
-------
Series
Series with the data type of the array elements.
Examples
--------
>>> s = pl.Series("a", [[1, 2, 3], [4, 5, 6]], dtype=pl.Array(pl.Int64, 3))
>>> s.arr.explode()
shape: (6,)
Series: 'a' [i64]
[
1
2
3
4
5
6
]
"""
def contains(
self, item: float | str | bool | int | date | datetime | time | IntoExprColumn
) -> Series:
"""
Check if sub-arrays contain the given item.
Parameters
----------
item
Item that will be checked for membership
Returns
-------
Series
Series of data type :class:`Boolean`.
Examples
--------
>>> s = pl.Series(
... "a", [[3, 2, 1], [1, 2, 3], [4, 5, 6]], dtype=pl.Array(pl.Int32, 3)
... )
>>> s.arr.contains(1)
shape: (3,)
Series: 'a' [bool]
[
true
true
false
]
"""
def count_matches(self, element: IntoExpr) -> Series:
"""
Count how often the value produced by `element` occurs.
Parameters
----------
element
An expression that produces a single value
Examples
--------
>>> s = pl.Series("a", [[1, 2, 3], [2, 2, 2]], dtype=pl.Array(pl.Int64, 3))
>>> s.arr.count_matches(2)
shape: (2,)
Series: 'a' [u32]
[
1
3
]
"""
def to_struct(
self,
fields: Callable[[int], str] | Sequence[str] | None = None,
) -> Series:
"""
Convert the series of type `Array` to a series of type `Struct`.
Parameters
----------
fields
If the name and number of the desired fields is known in advance
a list of field names can be given, which will be assigned by index.
Otherwise, to dynamically assign field names, a custom function can be
used; if neither are set, fields will be `field_0, field_1 .. field_n`.
Examples
--------
Convert array to struct with default field name assignment:
>>> s1 = pl.Series("n", [[0, 1, 2], [3, 4, 5]], dtype=pl.Array(pl.Int8, 3))
>>> s2 = s1.arr.to_struct()
>>> s2
shape: (2,)
Series: 'n' [struct[3]]
[
{0,1,2}
{3,4,5}
]
>>> s2.struct.fields
['field_0', 'field_1', 'field_2']
Convert array to struct with field name assignment by function/index:
>>> s3 = s1.arr.to_struct(fields=lambda idx: f"n{idx:02}")
>>> s3.struct.fields
['n00', 'n01', 'n02']
Convert array to struct with field name assignment by
index from a list of names:
>>> s1.arr.to_struct(fields=["one", "two", "three"]).struct.unnest()
shape: (2, 3)
┌─────┬─────┬───────┐
│ one ┆ two ┆ three │
│ --- ┆ --- ┆ --- │
│ i8 ┆ i8 ┆ i8 │
╞═════╪═════╪═══════╡
│ 0 ┆ 1 ┆ 2 │
│ 3 ┆ 4 ┆ 5 │
└─────┴─────┴───────┘
"""
s = wrap_s(self._s)
return s.to_frame().select(F.col(s.name).arr.to_struct(fields)).to_series()
def shift(self, n: int | IntoExprColumn = 1) -> Series:
"""
Shift array values by the given number of indices.
Parameters
----------
n
Number of indices to shift forward. If a negative value is passed, values
are shifted in the opposite direction instead.
Notes
-----
This method is similar to the `LAG` operation in SQL when the value for `n`
is positive. With a negative value for `n`, it is similar to `LEAD`.
Examples
--------
By default, array values are shifted forward by one index.
>>> s = pl.Series([[1, 2, 3], [4, 5, 6]], dtype=pl.Array(pl.Int64, 3))
>>> s.arr.shift()
shape: (2,)
Series: '' [array[i64, 3]]
[
[null, 1, 2]
[null, 4, 5]
]
Pass a negative value to shift in the opposite direction instead.
>>> s.arr.shift(-2)
shape: (2,)
Series: '' [array[i64, 3]]
[
[3, null, null]
[6, null, null]
]
"""