forked from johnros/polars_demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnested_dtypes.qmd
1046 lines (711 loc) · 19.1 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-12-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()
```
# Introduction
Recall the nested dtypes:
1. Polars Struct: Like a Python dict within a cell; Multiple named elements.
2. Polars List: Similar to a Python list within a cell; Multiple unnamed elements. Unlike the Python list, in a Polars list, all elements must have the same dtype.
3. Polars Array: Like a Polars list, but with a fixed length for all cells in the column.
# 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. There are differences between the two. For instance, all elements in a Polars list must have the same dtype. Also, the Polars list is a columnar data structure, which is more efficient for certain operations. Finally, the Polars list is a first-class citizen in the Polars API, with its own methods and functions.
- Can a Polars list hold a polars list? Yes. See the next example.
Make a Polars list of Polars 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 you will create one from a Polars DataFrame:
1. When grouping without aggregation.
2. When wrapping a bunch of columns with `pl.concat_list()`.
3. When "imploding" (aka "collapsing") an `pl.Expr()`.
List from aggregation:
```{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 concatenation of pl.Exprs():
```{python}
#| label: list-from-concatenation
df.select(pl.concat_list([pl.col("a"), pl.col("b")]))
```
List from concatenation of pl.Lists:
```{python}
(
df
.select(
pl.concat_list([pl.col("a"), pl.col("b")]).alias('ab')
)
.with_columns(pl.col('ab').list.concat('ab'))
.to_pandas()
)
```
List from imploding an `pl.Expr()`:
```{python}
#| label: list-from-imploding
df.with_columns(pl.col("b").implode())
```
Implode within group:
```{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")) # good!
```
See [here](https://github.com/pola-rs/polars/pull/6487) for more context.
### More on `.over(mapping_strategy=...)`
TODO
## Operating on List Elements
The most general way is to use `list.eval(pl.element())`:
```{python}
#| label: list-eval-element
df_with_list = df.with_columns(pl.concat_list([pl.col("a"), pl.col("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()`.
```{python}
#| label: list-eval-element-methods
print(dir(pl.element()))
```
## List Methods
`.list.eval(pl.element())` will operate one element at a time.
If you want to operate on the list as a whole, you can wither use existing [list methods](https://docs.pola.rs/py-polars/html/reference/expressions/list.html), or use `pl.col()` methods, after exploding the list (see @sec-list-explode).
We now demonstrate some of the list methods.
### Selecting Elements
Get, Gather, Slice, Gather_Every
```{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'),
)
)
```
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').list.sample(10, with_replacement=True).alias('within_row'),
pl.col('ab').sample(6, with_replacement=True).alias('within_column'),
)
.to_pandas()
)
```
### Filtering
```{python}
#| label: list-filter
(
df_with_list
.select(
pl.col('ab'),
pl.col('ab').list.eval(pl.element().gt(2)).alias('gt_2'),
# pl.col('ab').list.filter(pl.col('ab').list.gt(5)).alias('gt_5'), # not implemented yet
)
)
```
### Statistical Aggregations
.arg_max:
.arg_min:
.var:
.std:
.n_unique:
.unique:
.min:
.max:
.sum:
.mean:
.median:
.len
```{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
.sort:
.reverse:
```{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
.diff
```{python}
#| label: list-diff
(
df_with_list
.select(
pl.col('ab'),
pl.col('ab').list.diff().alias('diff'),
)
)
```
### 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
```{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('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'),
)
)
```
### 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
### Exporting to Other Nested Dtypes
```{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'),
)
)
```
### Examples
#### ECDF
```{python}
#| label: list-ecdf
(
df_with_list
.select(
pl.col('ab').alias('raw'),
pl.col('ab').list.eval(pl.element().rank()).alias('ranks'),
pl.col('ab').list.eval(pl.element().rank().truediv(2)).alias('ecdf_1'),
# pl.col('ab').list.eval(pl.element().rank().truediv(pl.col('ab').list.len())).alias('ecdf_2'),
)
)
```
Things to note:
- Currently, `.list.eval()` cannot reference another column. See [issue](https://github.com/pola-rs/polars/issues/7210).
- `.list.eval(pl.element())` can do more than point_wise operations. Think about the `rank()` example.
- `.rank()` has a `method` argument that can be used to specify how to deal with ties.
#### 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.
```{python}
#| label: arg-max-horizontal
(
df
.with_columns(
pl.concat_list([pl.col("a"), pl.col("b")]).list.arg_max().alias('arg_max'),
)
.select(
'a','b',
(
pl.col('arg_max')
.map_elements(lambda i: df.columns[i], return_dtype=pl.Utf8)
.alias('arg_max_col_name')
)
)
)
```
Things to note:
- Can you find a more efficient way to do this? Maybe using a struct?
## `.list.explode()` {#sec-list-explode}
Explode: "explode" the list onto a column.
```{python}
(
df_with_list
.select(
pl.col('ab').list.explode().alias('ab_exploded'),
)
)
```
Implode: "implode" the list back into a list.
```{python}
(
df_with_list
.select(
pl.col('ab').implode().alias('ab_imploded'),
pl.col('ab').list.explode().implode().alias('ab_exploded_imploded'),
)
)
```
Use group-wise to work on the list as a column.
```{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()`
```{python}
#| label: df-explode
df_with_list.explode('ab')
```
### Examples
#### Quantile
Recall there is no `.list.quantile()` method; so we need to brew our own.
```{python}
#| label: quantile-example
df_for_quantile = (
df_with_list
.select(
pl.col('ab').list.sample(100, with_replacement=True),
)
)
df_for_quantile.to_pandas()
```
```{python}
(
df_for_quantile
.with_row_index()
.group_by('index')
.agg(
pl.col('ab').explode().quantile(0.2)
)
)
```
Things to note:
1. The explode within row index is a powerful trick to apply any `pl.col()` method to a list.
2. There is another way to apply `pl.col()` methods to a list... With `.list.eval(pl.element())` as in the next example.
```{python}
(
df_for_quantile
.select(
pl.col('ab').list.eval(pl.element().quantile(0.2))
.list.first() # to extract a float from a list
.alias('quantile_0.2'),
)
)
```
## Polars Lists of Polars Lists
```{python}
#| label: list-of-list
df_with_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"]
}
)
df_with_list_of_list
```
List operations will work one level deep.
```{python}
#| label: list-of-list-inner
(
df_with_list_of_list
.select(
pl.col('a'),
pl.col('a').list.get(0).alias('get_1'),
# pl.col('a').list.gather([0]).alias('gather_1'), # returns a list
# pl.col('a').list.slice(0,1).alias('slice_1'), # returns a list
# pl.col('a').list.gather([0, 1]).alias('gather_2'),
# pl.col('a').list.slice(0,2).alias('slice_2'),
# pl.col('a').list.gather_every(2).alias('gather_every_2'),
)
)
```
## Examples
### Filter A List With A Predicte
```{python}
# Sample data
data = {
'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"],
],
}
# Create a polars DataFrame
df = pl.DataFrame(data)
df
```
In each list, keep only strings of length 4.
Syntax 1:
```{python}
(
df
.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')
)
```
Syntax 2:
```{python}
(
df
.with_row_index('i')
.with_columns(
(
(cntr:=pl.col('string_list').explode())
.filter(cntr.str.len_chars().eq(4))
)
.implode()
.over('i')
)
.drop('i')
)
```
Syntax 3:
```{python}
(
df
.select(
pl.col('string_list').list.gather(
pl.col('string_list').list.eval(
pl.arg_where(
pl.element().str.len_chars().eq(4)
)
)
)
)
)
```
# Polars Array {#sec-array}
Polars Arrays as Polars lists with a fixed length.
## Making a Polars Array
Make a Polars array from a Python list.
```{python}
#| label: make-array
pl.DataFrame(
[
pl.Series("Array_1", [[1, 3], [2, 5]]),
pl.Series("Array_2", [[1, 7, 3], [8, 1, 0]]),
],
schema={
"Array_1": pl.Array(pl.Int64, 2),
"Array_2": pl.Array(pl.Int64, 3),
},
)
```
Things to note:
- The dtype of the array is specified in the schema. Otherwise, a Polars list would have been inferred.
## Array Methods
Currently, list methods and array methods seem to be the same.
I expect these lists to diverge in the future, because more operations can be defined when assuming a fixed length.
# Polars Struct {#sec-struct}
## Making a Polars Struct
Make a Polars struct from a Python dict.
```{python}
#| label: make-struct
pl.DataFrame(
{
"a": [{"x": 1, "y": 2}, {"x": 3, "y": 4}, {"x": 5, "y": 6}],
"b": ["a", "b", "c"]
}
)
```
What are the differences between a Polars struct and a Python dict?
1. The Polars stuct must have the same keys (called `fields`) in all rows.
2. A Polars struct is a first-class citizen in the Polars API, with its own methods and functions.
3. Besides these, I am still figuring it out.
What are the differences between a Polars struct and a Polars list?
1. A Polars struct has named elements, while a Polars list has unnamed elements.
2. Because the struct has the same fields in all rows, it must have the same length in all rows. This is not the case for a Polars list.
More often you will not make a Polars struct directly, but rather you will create one from a Polars DataFrame:
1. By directly creating a struct.
2. As the output of some operation, like `pl.Expr().value_counts()`, or all the horizontal cumulators like `pl.cum_sum_horizontal()`, `pl.cum_reduce()`, `pl.cum_fold()`, ...
3. From a Polars list.
### Making a Polars Struct Directly
```{python}
#| label: make-struct-directly
df_with_struct = df.select(pl.struct(['a','b']).alias('struct'))
df_with_struct
```
Verify that the column is a struct:
```{python}
#| label: verify-struct
df_with_struct.schema
```
Alternative constructors
```{python}
df.select(pl.struct(aaa=pl.col('a'), bbb=pl.col('b'))).schema
```
### Struct As Output
```{python}
df.select(pl.col('a').value_counts())
# df.select(pl.col('a').value_counts()).schema
```
### Struct From List
```{python}
#| label: struct-from-list
df_with_list.select(pl.col('ab').list.to_struct())
```
## Struct Methods
### Extracting Elements
```{python}
#| label: struct-get
(
df_with_struct
.select(
pl.col('struct').struct.field('a'),
pl.col('struct').struct.field('b'),
)
)
```
To text in JSON format:
```{python}
#| label: struct-to-json
(
df_with_struct
.select(
pl.col('struct').struct.json_encode()
)
)
```
## Struct to List
There is no `.struct.to_list()` method.
This makes sense, since a struct does not require all fields to have the same dtype.
In the case where all fields have the same dtype, you can use the following.
```{python}
#| label: struct-to-list
(
df_with_struct
.unnest('struct')
.select(pl.concat_list(pl.all()))
)
```
You can also consider element-by-element extractions.
```{python}
#| label: struct-to-list-element-by-element
(
df_with_struct
.select(
pl.concat_list([
pl.col('struct').struct.field('a'),
pl.col('struct').struct.field('b')
])