-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnested_dtypes.qmd
1453 lines (943 loc) · 28.3 KB
/
nested_dtypes.qmd
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Nested dtypes"
execute:
eval: true
warning: true
error: true
keep-ipynb: true
cache: true
jupyter: python3
pdf-engine: lualatex
# theme: pandoc
html:
code-tools: true
fold-code: false
author: Jonathan D. Rosenblatt
data: 04-20-2024
toc: true
number-sections: true
number-depth: 3
embed-resources: true
---
```{python}
#| echo: false
# %pip install --upgrade pip
# %pip install --upgrade polars
# %pip install --upgrade pyarrow
# %pip install --upgrade Pandas
# %pip install --upgrade plotly
# %pip freeze > requirements.txt
```
```{python}
#| label: setup-env
# %pip install -r requirements.txt
```
```{python}
#| label: Polars-version
%pip show Polars # check you Polars version
```
```{python}
#| label: Pandas-version
%pip show Pandas # check you Pandas version
```
```{python}
#| label: preliminaries
import polars as pl
pl.Config(fmt_str_lengths=50)
import polars.selectors as cs
import pandas as pd
import numpy as np
import pyarrow as pa
import plotly.express as px
import string
import random
import os
import sys
%matplotlib inline
import matplotlib.pyplot as plt
from datetime import datetime
# Following two lines only required to view plotly when rendering from VScode.
import plotly.io as pio
# pio.renderers.default = "plotly_mimetype+notebook_connected+notebook"
pio.renderers.default = "plotly_mimetype+notebook"
```
What Polars module and dependencies are installed?
```{python}
#| label: show-versions
pl.show_versions()
```
How many cores are available for parallelism?
```{python}
#| label: show-cores
pl.thread_pool_size()
```
# Preliminaries
## A Polars Frame Can Hold Anything
Fun fact- Polars, like Pandas, can store anything within a cell. For instance, a Polars frame can hold a Polars frame.
```{python}
#| label: make-polars-frame
df = pl.DataFrame(
{
"a": [
pl.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}),
pl.DataFrame({"x": [7, 8, 9], "y": [10, 11, 12]})
],
"b": ["a", "b"]
}
)
print(df)
```
Things to note:
- The dtype of the frame is `Polars Object`.
## Motivation For Nested dtypes
Consider the following scenarios:
1. I want to compute with part-of-strings generated by a **split**.
2. I want to store and compute with arrays of **varying lengths**. Examples include: paths of cars on the globe, paths of users in a website,
3. I want to **group columns** together, and compute with them as a unit.
1. For convenience of access.
2. Because I am missing a `foo_horizontal()` method.
4. I want to read a JSON/XML/YML with **nested structures**.
How can I go about?
1. Since a Polars object, like a Python object, can hold anything, I could store the nested data as a **Polars object**.
1. I could generate **many columns**, and pad with nulls when lengths differ.
2. I could store each unit as a **Polars Series**.
The **Python object** option is always available, and I will try to **avoid it**.
If I can avoid Polars (i.e. Rust) calling Python, I will.
The second options could work. It is actually a good one, if I can figure out the **column access** (regex?).
The third option would be great. Unlike the first, I would remain within Rus. Unlike the second, I will have a **named unit** to access.
This is today's topic.
::: {.callout-important}
The Polars nested dtypes are inherited from the Arrow format.
So these are actually "Arrow Nested dtypes with Polars' functionality".
:::
## Nested dtypes in Polars
The Polars nested dtypes, inherited from [PyArrow](https://wesm.github.io/arrow-site-test/format/Layout.html):
1. **Polars List**
2. **Polars Array**
3. **Polars Struct**
A **Polars list** is a Polars Series within a cell: All elements in the cell must have the same dtype; the elements are unnamed so accessed by index or filter.
Do not be confused by the name. A Polars list is not a Python list.
A **Polars array** is a Polars list with a fixed length: All elements in the cell must have the same dtype and the same length; the elements are unnamed so accessed by index or filter. Another mental model of a Polars array is a numpy 2D array within a Polars frame.
A **Polars struct** is a Polars DataFrame within a cell: All elements in the cell must have the same fields; the elements are named so accessed by field name.
Do not think of the struct as a Python dict within a cell, because all rows must have the same fields.
# Polars List {#sec-list}
## Making a Polars List
Make a Polars list from a Python list.
```{python}
#| label: make-list
pl.DataFrame(
{
"a": [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
"b": ["a", "b", "c"]
}
)
```
Things to note:
- `a` is not a Python list, rather, it is a Polars list.
- Can a Polars list hold a Polars list? Yes. It can hold any Polars object, even nested ones (list of list of list, etc.); provided that all elements in the cell have the same dtype.
Make a Polars list of Python lists of Python lists:
```{python}
#| label: make-list-of-list
pl.DataFrame(
{
"a": [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]]],
"b": ["a", "b"]
}
)
```
More often you will not make a Polars list directly, but rather it will be the result of some operation:
1. When grouping without aggregation.
1. When splitting a string of unknown length (knonwn length will return a Polars struct, and I expect in the future a Polars array).
2. When wrapping a bunch of columns with `pl.concat_list()`.
3. When "imploding" (aka "collapsing") a columns.
### List from Aggregation
A Polars group_by, will actually create a Polars list internally, before applying the `.agg()` method.
```{python}
#| label: list-from-aggregation
df = pl.DataFrame(
{
"a": [1, 1, 2, 2, 3, 3],
"b": [1, 2, 3, 4, 5, 6]
}
)
df.group_by("a").agg(pl.col("b"))
```
### List From Splitting a String
```{python}
#| label: make-frame-with-string-to-split
df_strings = pl.DataFrame(
{
"a": ["apple, banana, orange", "apple, banana", "apple"],
}
)
df_strings
```
Now split `a` into... whatever Polars decides to return.
Hint: a Polars list of Polars strings.
```{python}
(
df_strings
.select(
pl.col('a').str.split(", ")
)
)
```
### List from Imploding a Column
```{python}
#| label: list-from-imploding
df.with_columns(pl.col("b").implode())
```
Try replacing `.with_columns()` with `.select()` and see what happens.
Implode `group_by()`:
```{python}
#| label: implode-within-group
df.group_by("a").agg(pl.col("b"))
```
Implode `over()`:
```{python}
#| label: implode-over
#| eval: false
df.with_columns(pl.col("b").over("a")) # no good
df.with_columns(pl.col("b").implode().over("a")) # no good
df.with_columns(pl.concat_list('b').over("a")) # no good
```
```{python}
(
df
.with_columns(
pl.col("b").over("a", mapping_strategy="join").alias('over_join'),
pl.col("b").over("a", mapping_strategy="explode").alias('over_explode'),
pl.col("b").over("a", mapping_strategy="group_to_rows").alias('over_group_to_rows'),
)
)
# good!
```
Things to note:
- The `mapping_strategy` argument govern the way the result within group is propagate to each row. Trying chainging its value to see the effect.
- See [here](https://github.com/pola-rs/polars/pull/6487) for more context on how `.over()` works and why.
### List From `pl.concat_list()`
```{python}
#| label: list-from-concatenation
df.select(pl.concat_list([pl.col("a"), pl.col("b")]))
```
### List From `.list.concat()`
```{python}
(
df
.with_columns(
pl.concat_list([pl.col("a"), pl.col("b")]).alias('ab')
)
.select(pl.col('ab').list.concat(['a','a','a']))
.to_pandas()
)
```
## Operating on List Elements
Arguably, the only motivation for using a Polars list, is for easy access to the list and its elements.
You are thus welcome to think of equivalent operations, without the `.list.` API.
An element can be accessed and trasformed with `list.eval(pl.element())`, which will expose (almost) all the methods of a `pl.Expr()` object.
```{python}
#| label: list-eval-element
df_with_list = (
df
.with_columns(
pl.concat_list(['a','b']).alias('ab')
)
)
(
df_with_list
.select(
pl.col('ab').list.eval(
pl.element().add(1000)
)
)
)
```
Things to note:
- `.eval()` belongs to the `.list` namespace.
- `pl.element()` is a selector that selects the elements of the list. It has almost all the methods available to `pl.col()`.
- `.eval()` currently cannot access other columns. You will probably discover this is a considerable limitation.
```{python}
#| label: list-eval-element-methods
print(dir(pl.element()))
```
`list.eval(pl.element())`, however, does not see to add much that cannot be done with `pl.col()` methods.
The true power of the `.list` namespace, is in is pre-defined methods.
## List Methods
### Accessing Elements
Recall; list elements are unnamed. They are thus accessed using indices (`iloc[]` style).
```{python}
#| label: list-get-and-gather
(
df_with_list.select(
pl.col('ab'),
pl.col('ab').list.get(0).alias('get_1'),
pl.col('ab').list.gather([0]).alias('gather_1'), # returns a list
pl.col('ab').list.slice(0,1).alias('slice_1'), # returns a list
pl.col('ab').list.gather([0, 1]).alias('gather_2'),
pl.col('ab').list.slice(0,2).alias('slice_2'),
pl.col('ab').list.gather_every(2).alias('gather_every_2'),
)
)
```
Things to note:
- What returns a list, and what returns a single element?
First, Head, Last, Tail
```{python}
#| label: list-methods
(
df_with_list.select(
pl.col('ab'),
pl.col('ab').list.get(1).alias('first_1'),
pl.col('ab').list.first().alias('first_2'),
pl.col('ab').list.head(1).alias('first_5'), # returns a list
pl.col('ab').list.last().alias('last_2'),
pl.col('ab').list.tail(1).alias('last_1'), # returns a list
pl.col('ab').list.tail(1).list.first().alias('last_3'),
)
)
```
Shift
```{python}
#| label: list-shift
(
df_with_list.select(
pl.col('ab'),
pl.col('ab').list.shift(1).alias('shift_1'),
pl.col('ab').list.shift(-1).alias('shift_-1'),
)
)
```
Sample
```{python}
#| label: list-sample
(
df_with_list.select(
pl.col('ab'),
pl.col('ab').list.sample(10, with_replacement=True).alias('sample'),
)
.to_pandas()
)
```
Careful where you put the `.sample()`!
```{python}
(
df_with_list
.select(
pl.col('ab'),
pl.col('ab').list.sample(10, with_replacement=True).alias('within_row'),
pl.col('ab').sample(6, with_replacement=True).alias('within_column'),
)
.to_pandas()
)
```
### Statistical Aggregations
```{python}
#| label: list-statistical-aggregations
(
df_with_list
.select(
pl.col('ab'),
pl.col('ab').list.min().alias('min'),
pl.col('ab').list.max().alias('max'),
pl.col('ab').list.sum().alias('sum'),
pl.col('ab').list.mean().alias('mean'),
pl.col('ab').list.median().alias('median'),
pl.col('ab').list.var().alias('var'),
pl.col('ab').list.std().alias('std'),
pl.col('ab').list.n_unique().alias('n_unique'),
pl.col('ab').list.unique().alias('unique'),
pl.col('ab').list.len().alias('len'),
)
)
```
### Ordering and Ranking
```{python}
#| label: list-ordering-and-ranking
(
df_with_list
.select(
pl.col('ab'),
# pl.col('ab').list.rank().alias('rank'),
pl.col('ab').list.sort().alias('sort'),
pl.col('ab').list.reverse().alias('reverse'),
)
)
```
### Sequence Operations
```{python}
#| label: list-diff
(
df_with_list
.select(
pl.col('ab'),
pl.col('ab').list.diff().alias('diff'),
)
)
```
What about `.pct_change()`?
The following will not work, but see @sec-pct-change for a workaround.
```{python}
#eval: false
(
df_with_list
.select(
pl.col('ab'),
pl.col('ab').list.pct_change().alias('pct_change'),
)
)
```
### Logical Aggregations
```{python}
#| label: list-logical-aggregations
(
df_with_list
.select(
pl.col('ab'),
pl.col('ab').list.eval(pl.element().eq(1)).list.any().alias('any'),
pl.col('ab').list.eval(pl.element().eq(1)).list.all().alias('all'),
)
)
```
### String Operations
- `list.join()` will join the strings in the list. I admit, I would have expected a `.list.str.concat()` instead.
- `list.contains()` will check if the list contains a string.
- `list.count_matches()` will count the number of times a string appears in the list.
```{python}
#| label: list-strings
df_2_with_list = pl.DataFrame(
{
"ab": [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]],
'sep': ['@', '#', '$']
}
)
(
df_2_with_list
.select(
pl.col('ab'),
pl.col('sep'),
pl.col('ab').list.join(pl.col('sep')).alias('joined'),
pl.col('ab').list.contains('a').alias('contains_a'),
pl.col('ab').list.count_matches('a').alias('count_a'),
)
)
```
### Filtering
Currently there is no `.list.filter()` method (see [issue](https://github.com/pola-rs/polars/issues/9189)).
There are, however, many workarounds.
#### Option 1: Using `pl.element().filter()`
```{python}
#| label: list-filter
(
df_with_list
.select(
pl.col('ab'),
pl.col('ab').list.eval(
pl.element()
.filter(pl.element().gt(2)),
)
.alias('gt_2'),
)
)
```
#### Option 2: Using `.list.gather()` + `pl.arg_where()`
Let's try to filter elements of a list based on the length of the string.
```{python}
# Sample data
data = pl.DataFrame({
'string_list': [
["apple", "banana", "orange", "grape", "pear"],
["apple", "banana", "orange", "grape"],
["apple", "banana", "orange"],
["apple", "banana"],
["apple"],
["apple", "banana", "orange", "grape", "pear"],
["apple", "banana", "orange", "grape"],
],
}
)
```
In each list, keep only strings of length 4.
Using `.list.gather()` and `pl.arg_where()` and explode to access `pl.col().str` methods.
```{python}
(
data
.with_row_index('i')
.with_columns(
pl.col('string_list').list.gather(
pl.arg_where(
pl.col('string_list').explode().str.len_chars().eq(4))
)
.over('i')
)
.drop('i')
)
```
Without exploding: Using `list.gather()` to filter, and `list.eval()` to access `pl.element().str` methods.
```{python}
(
data
.select(
pl.col('string_list').list.gather(
pl.col('string_list').list.eval(
pl.arg_where(
pl.element().str.len_chars().eq(4)
)
)
)
)
)
```
Explode once, and call the output twice using the Walrus operator; once to access `pl.col().filter()` and then to access `pl.col().str`.
```{python}
(
data
.with_row_index('i')
.with_columns(
(
(cntr := pl.col('string_list').explode())
.filter(cntr.str.len_chars().eq(4))
)
.implode()
.over('i')
)
.drop('i')
)
```
Things to note:
- If you are unfamilar with Python's (not Polars') Walrus operator `:=`, see [here](https://realpython.com/python-walrus-operator/).
### Missing
I believe everything can be done with `.list.eval(pl.element().method())`.
### Set Operations
.list.set_intersection
.list.set_union
.list.set_difference
.list.set_symmetric_difference
```{python}
(
df_with_list
.select(
pl.col('ab'),
pl.col('ab').list.set_intersection([1,2,3]).alias('intersection'),
pl.col('ab').list.set_union(['11']).alias('union'),
pl.col('ab').list.set_union(['a']).alias('union_2'),
pl.col('ab').list.set_difference([2,3]).alias('difference'),
pl.col('ab').list.set_symmetric_difference([1,2,3]).alias('symmetric_difference'),
)
)
```
Things to note:
- We can pass a Python list and not a Python set.
- Set union with an appropriate dtype will return Null. Is that what you would expect?
### Polars List to Array or Struct
```{python}
#| label: list-to-struct
(
df_with_list
.select(
pl.col('ab'),
pl.col('ab').list.to_struct().alias('ab_struct'),
pl.col('ab').list.to_array(width=2).alias('ab_array'),
)
)
```
Things to note:
- An array has a fixed length; it is not inferred, you must specify it.
## Exploding and Imploding {#sec-list-explode}
**Explode**: from list onto a column.
```{python}
(
df_with_list
.select(
pl.col('ab').list.explode().alias('ab_exploded'),
)
)
```
**Implode**: from column to list.
```{python}
(
df_with_list
.select(
pl.col('ab').implode().alias('ab_imploded'),
pl.col('ab').list.explode().implode().alias('ab_exploded_imploded'),
)
)
```
::: {.callout-important}
The following is a great trick to use when the `.list` namespace does not have the method you need.
:::
Explode within a group will convert the list to a column, on which you can operate using usual `pl.col()` methods.
```{python}
(
df_with_list
.with_row_index()
.group_by('index')
.agg(
pl.col('ab').list.explode()
.alias('this_is_actually_a_column'),
)
)
```
There is also `df.explode()`, alongside the `pl.col().explode()` method.
```{python}
#| label: df-explode
df_with_list.explode('ab')
```
## Examples
#### pct_change {#sec-pct-change}
In the absence of a `.list.pct_change()` method, we can use the following workaround.
```{python}
(
df_with_list
.with_row_index()
.group_by('index')
.agg(
pl.col('ab').list.explode().pct_change().alias('pct_change'),
)
)
```
Could I have done that with the multiple column approach?
Would have needed `pl.col.pct_change_horizontal()`.
#### ECDF {#sec-ecdf}
How to compute within a column?
In the abcense of `.list.ecdf()` and `pl.order_horizontal()`, we can use the following.
```{python}
#| label: list-ecdf
(
df_with_list
.select(
pl.col('ab'),
# Ranks
pl.col('ab').list.eval(pl.element().rank()).alias('ranks'),
# Option 1:ECDF with hard coded length (makes sense for an array)
pl.col('ab').list.eval(pl.element().rank().truediv(2)).alias('ecdf_1'),
# Option 2: ECDF with length of list. Will not work.
# pl.col('ab').list.eval(pl.element().rank().truediv(pl.col('ab').list.len())).alias('ecdf_2'),
)
)
```
Things to note:
- `.list.eval(pl.element())` can do more than point_wise operations. Think about the `rank()` example.
- Option 2 will fail because `.list.eval()` cannot reference another column. See [issue](https://github.com/pola-rs/polars/issues/7210).
- `.rank()` has a `method` argument that can be used to specify how to deal with ties.
Here is another attempt, which does not assume the length of the list is known (not fixed).
The following will not work, but may be fixed.
```{python}
(
df_with_list
.with_row_index()
.group_by('index')
.agg(
(abrank:=pl.col('ab').explode().rank()).truediv(abrank.len()),
)
)
```
#### ECDF wrt Other Column
@sec-ecdf showed how to compute the ECDF of a list. Say we want to evaluate the ECDF of column `a` wrt column `b`.
TODO
```{python}
#| eval: false
(
df_with_list
.with_columns(pl.col('a').implode())
.with_row_index()
.group_by('index')
.agg(
(
a_ge_b_ind := pl.col('a').explode().ge(pl.col('b'))
)
)
.with_columns(
a_ge_b_ind.list.sum().truediv(a_ge_b_ind.list.len())
)
)
```
#### arg_max_horizontal
Note, there currently is no `pl.arg_max_horizontal()` method.
We will try to make one by concatenating columns to list, and then using the `.list.arg_max()`.
In particular, we will want the arg_max col name, and not the index.