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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f57b8b5
4c17152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# /// script
# requires-python = ">=3.13"
# dependencies = [
#     "marimo",
#     "polars==1.23.0",
# ]
# ///

import marimo

__generated_with = "0.11.13"
app = marimo.App(width="medium")


@app.cell
def _():
    import marimo as mo
    return (mo,)


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        # Basic operations on data
        _By [Joram Mutenge](https://www.udemy.com/user/joram-mutenge/)._

        In this notebook, you'll learn how to perform arithmetic operations, comparisons, and conditionals on a Polars dataframe. We'll work with a DataFrame that tracks software usage by year, categorized as either Vintage (old) or Modern (new).
        """
    )
    return


@app.cell
def _():
    import polars as pl

    df = pl.DataFrame(
        {
            "software": [
                "Lotus-123",
                "WordStar",
                "dBase III",
                "VisiCalc",
                "WinZip",
                "MS-DOS",
                "HyperCard",
                "WordPerfect",
                "Excel",
                "Photoshop",
                "Visual Studio",
                "Slack",
                "Zoom",
                "Notion",
                "Figma",
                "Spotify",
                "VSCode",
                "Docker",
            ],
            "users": [
                10000,
                4500,
                2500,
                3000,
                1800,
                17000,
                2200,
                1900,
                500000,
                12000000,
                1500000,
                3000000,
                4000000,
                2000000,
                2500000,
                4500000,
                6000000,
                3500000,
            ],
            "category": ["Vintage"] * 8 + ["Modern"] * 10,
            "year": [
                1985,
                1980,
                1984,
                1979,
                1991,
                1981,
                1987,
                1982,
                1987,
                1990,
                1997,
                2013,
                2011,
                2016,
                2016,
                2008,
                2015,
                2013,
            ],
        }
    )

    df
    return df, pl


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        ## Arithmetic
        ### Addition
        Let's add 42 users to each piece of software. This means adding 42 to each value under **users**.
        """
    )
    return


@app.cell
def _(df, pl):
    df.with_columns(pl.col("users") + 42)
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""Another way to perform the above operation is using the built-in function.""")
    return


@app.cell
def _(df, pl):
    df.with_columns(pl.col("users").add(42))
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        ### Subtraction
        Let's subtract 42 users to each piece of software.
        """
    )
    return


@app.cell
def _(df, pl):
    df.with_columns(pl.col("users") - 42)
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""Alternatively, you could subtract like this:""")
    return


@app.cell
def _(df, pl):
    df.with_columns(pl.col("users").sub(42))
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        ### Division
        Suppose the **users** values are inflated, we can reduce them by dividing by 1000. Here's how to do it.
        """
    )
    return


@app.cell
def _(df, pl):
    df.with_columns(pl.col("users") / 1000)
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""Or we could do it with a built-in expression.""")
    return


@app.cell
def _(df, pl):
    df.with_columns(pl.col("users").truediv(1000))
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""If we didn't care about the remainder after division (i.e remove numbers after decimal point) we could do it like this.""")
    return


@app.cell
def _(df, pl):
    df.with_columns(pl.col("users").floordiv(1000))
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        ### Multiplication
        Let's pretend the *user* values are deflated and increase them by multiplying by 100.
        """
    )
    return


@app.cell
def _(df, pl):
    (df.with_columns(pl.col("users") * 100))
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""Polars also has a built-in function for multiplication.""")
    return


@app.cell
def _(df, pl):
    df.with_columns(pl.col("users").mul(100))
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""So far, we've only modified the values in an existing column. Let's create a column **decade** that will represent the years as decades. Thus 1985 will be 1980 and 2008 will be 2000.""")
    return


@app.cell
def _(df, pl):
    (df.with_columns(decade=pl.col("year").floordiv(10).mul(10)))
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""We could create a new column another way as follows:""")
    return


@app.cell
def _(df, pl):
    df.with_columns((pl.col("year").floordiv(10).mul(10)).alias("decade"))
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        **Tip**  
        Polars encounrages you to perform your operations as a chain. This enables you to take advantage of the query optimizer. We'll build upon the above code as a chain.

        ## Comparison
        ### Equal
        Let's get all the software categorized as Vintage.
        """
    )
    return


@app.cell
def _(df, pl):
    (
        df.with_columns(decade=pl.col("year").floordiv(10).mul(10))
        .filter(pl.col("category") == "Vintage")
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""We could also do a double comparison. VisiCal is the only software that's vintage and in the decade 1970s. Let's perform this comparison operation.""")
    return


@app.cell
def _(df, pl):
    (
        df.with_columns(decade=pl.col("year").floordiv(10).mul(10))
        .filter(pl.col("category") == "Vintage")
        .filter(pl.col("decade") == 1970)
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        We could also do this comparison in one line, if readability is not a concern

        **Notice** that we must enclose the two expressions between the `&` with parenthesis.
        """
    )
    return


@app.cell
def _(df, pl):
    (
        df.with_columns(decade=pl.col("year").floordiv(10).mul(10))
        .filter((pl.col("category") == "Vintage") & (pl.col("decade") == 1970))
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""We can also use the built-in function for equal to comparisons.""")
    return


@app.cell
def _(df, pl):
    (df
     .with_columns(decade=pl.col('year').floordiv(10).mul(10))
     .filter(pl.col('category').eq('Vintage'))
     )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        ### Not equal
        We can also compare if something is `not` equal to something. In this case, category is not vintage.
        """
    )
    return


@app.cell
def _(df, pl):
    (df
     .with_columns(decade=pl.col('year').floordiv(10).mul(10))
     .filter(pl.col('category') != 'Vintage')
     )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""Or with the built-in function.""")
    return


@app.cell
def _(df, pl):
    (df
     .with_columns(decade=pl.col('year').floordiv(10).mul(10))
     .filter(pl.col('category').ne('Vintage'))
     )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""Or if you want to be extra clever, you can use the negation symbol `~` used in logic.""")
    return


@app.cell
def _(df, pl):
    (df
     .with_columns(decade=pl.col('year').floordiv(10).mul(10))
     .filter(~pl.col('category').eq('Vintage'))
     )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        ### Greater than
        Let's get the software where the year is greater than 2008 from the above dataframe.
        """
    )
    return


@app.cell
def _(df, pl):
    (df
     .with_columns(decade=pl.col('year').floordiv(10).mul(10))
     .filter(~pl.col('category').eq('Vintage'))
     .filter(pl.col('year') > 2008)
     )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""Or if we wanted the year 2008 to be included, we could use great or equal to.""")
    return


@app.cell
def _(df, pl):
    (df
     .with_columns(decade=pl.col('year').floordiv(10).mul(10))
     .filter(~pl.col('category').eq('Vintage'))
     .filter(pl.col('year') >= 2008)
     )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""We could do the previous two operations with built-in functions. Here's with greater than.""")
    return


@app.cell
def _(df, pl):
    (df
     .with_columns(decade=pl.col('year').floordiv(10).mul(10))
     .filter(~pl.col('category').eq('Vintage'))
     .filter(pl.col('year').gt(2008))
     )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""And here's with greater or equal to""")
    return


@app.cell
def _(df, pl):
    (df
     .with_columns(decade=pl.col('year').floordiv(10).mul(10))
     .filter(~pl.col('category').eq('Vintage'))
     .filter(pl.col('year').ge(2008))
     )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        **Note**: For "less than", and "less or equal to" you can use the operators `<` or `<=`. Alternatively, you can use built-in functions `lt` or `le` respectively.

        ### Is between
        Polars also allows us to filter between a range of values. Let's get the modern software were the year is between 2013 and 2016. This is inclusive on both ends (i.e. both years are part of the result).
        """
    )
    return


@app.cell
def _(df, pl):
    (df
     .with_columns(decade=pl.col('year').floordiv(10).mul(10))
     .filter(pl.col('category').eq('Modern'))
     .filter(pl.col('year').is_between(2013, 2016))
     )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        ### Or operator
        If we only want either one of the conditions in the comparison to be met, we could use `|`, which is the `or` operator.

        Let's get software that is either modern or used in the decade 1980s.
        """
    )
    return


@app.cell
def _(df, pl):
    (df
     .with_columns(decade=pl.col('year').floordiv(10).mul(10))
     .filter((pl.col('category') == 'Modern') | (pl.col('decade') == 1980))
     )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        ## Conditionals
        Polars also allows you create new columns based on a condition. Let's create a column *status* that will indicate if the software is "discontinued" or "in use".

        Here's a list of products that are no longer in use.
        """
    )
    return


@app.cell
def _():
    discontinued_list = ['Lotus-123', 'WordStar', 'dBase III', 'VisiCalc', 'MS-DOS', 'HyperCard']
    return (discontinued_list,)


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""Here's how we can get a dataframe of the products that are discontinued.""")
    return


@app.cell
def _(df, discontinued_list, pl):
    (df
     .with_columns(decade=pl.col('year').floordiv(10).mul(10))
     .filter(pl.col('software').is_in(discontinued_list))
     )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""Now, let's create the **status** column.""")
    return


@app.cell
def _(df, discontinued_list, pl):
    (df
     .with_columns(decade=pl.col('year').floordiv(10).mul(10))
     .with_columns(pl.when(pl.col('software').is_in(discontinued_list))
                   .then(pl.lit('Discontinued'))
                   .otherwise(pl.lit('In use'))
                   .alias('status')
                   )
     )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        ## Unique counts
        Sometimes you may want to see only the unique values in a column. Let's check the unique decades we have in our DataFrame.
        """
    )
    return


@app.cell
def _(df, discontinued_list, pl):
    (df
     .with_columns(decade=pl.col('year').floordiv(10).mul(10))
     .with_columns(pl.when(pl.col('software').is_in(discontinued_list))
                   .then(pl.lit('Discontinued'))
                   .otherwise(pl.lit('In use'))
                   .alias('status')
                   )
     .select('decade').unique()
     )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""Finally, let's find out the number of software used in each decade.""")
    return


@app.cell
def _(df, discontinued_list, pl):
    (df
     .with_columns(decade=pl.col('year').floordiv(10).mul(10))
     .with_columns(pl.when(pl.col('software').is_in(discontinued_list))
                   .then(pl.lit('Discontinued'))
                   .otherwise(pl.lit('In use'))
                   .alias('status')
                   )
     ['decade'].value_counts()
     )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""We could also rewrite the above code as follows:""")
    return


@app.cell
def _(df, discontinued_list, pl):
    (df
     .with_columns(decade=pl.col('year').floordiv(10).mul(10))
     .with_columns(pl.when(pl.col('software').is_in(discontinued_list))
                   .then(pl.lit('Discontinued'))
                   .otherwise(pl.lit('In use'))
                   .alias('status')
                   )
     .select('decade').to_series().value_counts()
     )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""Hopefully, we've picked your interest to try out Polars the next time you analyze your data.""")
    return


@app.cell
def _():
    return


if __name__ == "__main__":
    app.run()