forked from PPBDS/tutorial.helpers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtutorial.Rmd
More file actions
1023 lines (711 loc) · 30.5 KB
/
tutorial.Rmd
File metadata and controls
1023 lines (711 loc) · 30.5 KB
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: Introduction to Python
author: Satvika Upperla
tutorial:
id: introduction-to-python
output:
learnr::tutorial:
df_print: default
progressive: yes
allow_skip: yes
runtime: shiny_prerendered
description: Tutorial for introducing students to the Python language.
---
<!-- Do the test cases need to have all the Python commands? Or does the tutorial magically know that import polars . . . has already been run? -->
<!-- Learn about reticulate. -->
```{r setup, include=FALSE}
# -------------------------------------------------------------------
# Global setup: R packages + Python virtualenv for the tutorial
# -------------------------------------------------------------------
# Don't let reticulate auto-pick some random Python
Sys.setenv(RETICULATE_AUTOCONFIGURE = "FALSE")
# ---- interactive-only installs ----
needed <- c("learnr", "tutorial.helpers", "knitr", "reticulate")
to_install <- setdiff(needed, rownames(installed.packages()))
if (interactive() && length(to_install)) {
install.packages(to_install, quiet = TRUE)
}
# SU: for the above im thinking of just taking it out and moving knitr and reticulate out of suggests and into imports in the description file to, which presumably do the same thing as above
library(learnr)
library(tutorial.helpers)
library(knitr)
library(reticulate)
knitr::opts_chunk$set(echo = FALSE, out.width = "90%")
learnr::tutorial_options(
exercise.timelimit = 60,
exercise.startover = TRUE
)
## CI stuff to check if the tutorial is being run in github actions and R CMD Check, because then the check wil fail because it cant run python packages or modify the env, like the venv
# ---- Environment flags ----
is_windows <- identical(.Platform$OS.type, "windows")
# Do we need in_ci? What does it mean?
in_ci <- identical(tolower(Sys.getenv("CI")), "true") ||
identical(tolower(Sys.getenv("R_CMD_CHECK")), "true")
venv <- ".venv"
py_bin <- if (is_windows) file.path(venv, "Scripts", "python.exe") else file.path(venv, "bin", "python")
if (in_ci) {
# -----------------------------------------------------------------
# CI / R CMD check: render-only, no Python execution or venv setup
# -----------------------------------------------------------------
knitr::knit_engines$set(
python = function(options) {
knitr::engine_output(
options,
code = options$code,
out = "\n<!-- python execution skipped in CI / R CMD check -->\n"
)
}
)
} else {
# -----------------------------------------------------------------
# Local use: create/activate .venv in this tutorial directory
# -----------------------------------------------------------------
# 1) Find a system Python
python_exe <- Sys.which(if (is_windows) "python" else "python3")
if (!nzchar(python_exe)) {
python_exe <- reticulate::py_discover_config()$python
}
if (!nzchar(python_exe)) {
stop("No usable system Python found to create .venv.")
}
# 2) Create .venv if missing (do NOT delete if it already exists)
if (!dir.exists(venv)) {
message("Creating .venv with: ", python_exe)
reticulate::virtualenv_create(envname = venv, python = python_exe)
}
# 3) Point reticulate at this venv
Sys.setenv(RETICULATE_PYTHON = normalizePath(py_bin, winslash = "/", mustWork = FALSE))
reticulate::use_virtualenv(venv, required = TRUE)
# 4) Upgrade pip tooling via `python -m pip` (portable, no pip.exe assumption)
system2(
py_bin,
c("-m", "pip", "install", "--upgrade", "pip", "setuptools", "wheel"),
stdout = TRUE,
stderr = TRUE
)
# 5) Install required Python packages into this .venv
req <- c("polars", "pandas", "numpy", "plotnine", "matplotlib", "seaborn")
system2(py_bin, c("-m", "pip", "install", req), stdout = TRUE, stderr = TRUE)
# 6) Tell knitr to use reticulate's Python engine
knitr::knit_engines$set(python = reticulate::eng_python)
}
```
```{r copy-code-chunk, child = system.file("child_documents/copy_button.Rmd", package = "tutorial.helpers")}
```
```{r info-section, child = system.file("child_documents/info_section.Rmd", package = "tutorial.helpers")}
```
<!-- DK: List resources you found useful. -->
### Introduction
##
<!-- DK: Clean up. -->
This is tutorial introduces you to Python from a data science standpoint. We will explore Polars, a python data frame for data processing, that is more fast and efficient at handling large datasets over Pandas and Numpy two other python data frames.
<!-- DK: Also, start by explaining, in one sentence, what Python is, along with a link or two. -->
This tutorial introduces you to the Python language. Our approach is inspired by the data science workflow commonly used with Python's data analysis libraries. You will learn how to work with data sets using **polars**, a blazingly fast DataFrame library that uses a syntax similar to R's tidyverse. You will learn how to chain operations using method chaining with pipes, and how to make plots using **plotnine**, which implements the grammar of graphics just like ggplot2 in R.
###
This tutorial assumes that you have already completed the "Getting Started" tutorial in the [**tutorial.helpers**](https://ppbds.github.io/tutorial.helpers/) package. If you haven't, do so now. It is quick!
###
From the main Positron menu, start a new window with `File -> New Window`. This new window is the location in which you will do all the work for the tutorial. The current window, the one in which you are reading these words, is just used to run this tutorial.
## Working with data
###
Learn how to explore a data set using functions like `describe()`, `info()`, and `sample()`.
### Exercise 1
Before you start doing data science, you must import the libraries you are going to use. Use the `import` statement to load the **polars** library with the alias `pl`. This is the standard convention in Python. Click "Run Code." The check mark which appears next to "Exercise 1" above indicates that you have submitted your answer.
```{python working-with-data-1, exercise = TRUE}
```
```{python working-with-data-1-hint-1, eval = FALSE}
import ... as pl
```
```{python working-with-data-1-test, include = FALSE}
import polars as pl
```
###
In Python, we import libraries to access their functions and data. The `import` statement makes the library available, and using `as pl` creates a short alias so we can type `pl` instead of `polars` every time.
### Exercise 2
In this tutorial, you will sometimes enter code into the exercise blocks, as you did above. But we will also ask you to run code in the Python Console. (You will do this in the other Positron window, since the Console in this window is currently running this tutorial.) Example:
In the Python Console, run `import polars as pl`.
With Console questions, we will usually ask you to **C**opy/**P**aste the **C**ommand/**R**esponse into an answer block, like the one below. We usually shorten those instructions as CP/CR. Do that now.
```{r working-with-data-2}
question_text(NULL,
answer(NULL, correct = TRUE),
allow_retry = TRUE,
try_again_button = "Edit Answer",
incorrect = NULL,
rows = 5)
```
###
Your answer should look like:
```
>>> import polars as pl
>>>
```
Your answer never needs to match ours perfectly. Our goal is just to ensure that you are actually following the instructions.
### Exercise 3
DataFrames are spreadsheet-like data structures in Polars. Let's load the famous iris dataset. We'll read it from a URL.
In the Console, run:
```
import polars as pl
iris = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
iris
```
CP/CR.
```{r working-with-data-3}
question_text(NULL,
answer(NULL, correct = TRUE),
allow_retry = TRUE,
try_again_button = "Edit Answer",
incorrect = NULL,
rows = 15)
```
###
```{python working-with-data-3-test, echo = TRUE}
import polars as pl
iris = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
iris
```
Whenever we show outputs like this after a question, then we are showing our answer to the previous question, even if we do not label it as such.
### Exercise 4
In the Console, run `iris.describe()`. This provides summary statistics for numerical columns.
CP/CR.
```{r working-with-data-4}
question_text(NULL,
answer(NULL, correct = TRUE),
allow_retry = TRUE,
try_again_button = "Edit Answer",
incorrect = NULL,
rows = 10)
```
###
```{python working-with-data-4-test, echo = TRUE}
import polars as pl
iris = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
iris.describe()
```
###
This method provides a quick statistical overview of each numerical variable in the dataset. In some cases, the tutorial displays the same object differently from what you were able to copy/paste. And that is OK! Your answer does not need to match our answer.
### Exercise 5
In the Console, run `iris.sample()`. This selects a random row from the dataset.
CP/CR.
```{r working-with-data-5}
question_text(NULL,
answer(NULL, correct = TRUE),
allow_retry = TRUE,
try_again_button = "Edit Answer",
incorrect = NULL,
rows = 7)
```
###
```{python working-with-data-5-test, echo = TRUE}
import polars as pl
iris = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
iris.sample()
```
###
Your answer will differ from this answer because of the inherent randomness in methods like `sample()`.
### Exercise 6
In the Console, hit the Up Arrow to retrieve the previous command. Edit it to add the argument `n = 4` to `iris.sample()`. This will return 4 random rows from the `iris` dataset.
CP/CR.
```{r working-with-data-6}
question_text(NULL,
answer(NULL, correct = TRUE),
allow_retry = TRUE,
try_again_button = "Edit Answer",
incorrect = NULL,
rows = 10)
```
###
```{python working-with-data-6-test, echo = TRUE}
import polars as pl
iris = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
iris.sample(n = 4)
```
###
Editing code directly in the Console quickly becomes annoying. See the **[positron.tutorials](https://ppbds.github.io/positron.tutorials/)** package for tutorials about using Positron to write and organize your code.
### Exercise 7
In the Console, run `print(iris)`. This returns the same result as typing `iris`.
CP/CR.
```{r working-with-data-7}
question_text(NULL,
answer(NULL, correct = TRUE),
allow_retry = TRUE,
try_again_button = "Edit Answer",
incorrect = NULL,
rows = 10)
```
###
```{python working-with-data-7-test, echo = TRUE}
import polars as pl
iris = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
print(iris)
```
###
You can control how many rows to display using `iris.head(n)` for the first n rows or `iris.tail(n)` for the last n rows.
### Exercise 8
In the Console, run `iris.head(3)`. This returns the first 3 rows of the `iris` dataset.
CP/CR.
```{r working-with-data-8}
question_text(NULL,
answer(NULL, correct = TRUE),
allow_retry = TRUE,
try_again_button = "Edit Answer",
incorrect = NULL,
rows = 8)
```
###
```{python working-with-data-8-test, echo = TRUE}
import polars as pl
iris = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
iris.head(3)
```
###
`head()` by default gives the top of the DataFrame, so your answer should match our answer. `sample()`, on the other hand, picks random rows to return. But, in both cases, the result is a DataFrame.
A central organizing principle of Polars is that most methods take a DataFrame and return a DataFrame. This allows us to "chain" commands together, one after the other, creating a pipeline very similar to R's pipe operator `|>`.
### Exercise 9
In the Console, run `help(iris)` or `iris.info()`.
The `info()` method will show you information about the DataFrame including column names, data types, and memory usage.
Copy/paste the output of `iris.info()` below.
```{r working-with-data-9}
question_text(NULL,
answer(NULL, correct = TRUE),
allow_retry = TRUE,
try_again_button = "Edit Answer",
incorrect = NULL,
rows = 10)
```
###
You can find help about pandas functions with `help(function_name)` or by visiting the pandas documentation at https://pandas.pydata.org/.
### Exercise 10
In the Console, run `iris.schema`. This shows the column names and data types. CP/CR.
```{r working-with-data-10}
question_text(NULL,
answer(NULL, correct = TRUE),
allow_retry = TRUE,
try_again_button = "Edit Answer",
incorrect = NULL,
rows = 10)
```
###
```{python working-with-data-10-test, echo = TRUE}
import polars as pl
iris = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
iris.schema
```
###
The `schema` attribute displays information about the DataFrame's structure including the data types of each column. For example, `sepal_length` is listed as `Float64`, meaning it's a 64-bit floating-point number. You can also use `iris.dtypes` to see just the data types, or `iris.columns` to see just the column names.
### Exercise 11
In the Console, run `import math` then `math.sqrt(144)`.
CP/CR.
```{r working-with-data-11}
question_text(NULL,
answer(NULL, correct = TRUE),
allow_retry = TRUE,
try_again_button = "Edit Answer",
incorrect = NULL,
rows = 5)
```
###
```{python working-with-data-11-test, echo = TRUE}
import math
math.sqrt(144)
```
###
The square root function is one of many built-in functions in Python's math module. Most return their result, which Python then, by default, prints out.
### Exercise 12
In the Console, run `x = math.sqrt(144)`.
CP/CR.
```{r working-with-data-12}
question_text(NULL,
answer(NULL, correct = TRUE),
allow_retry = TRUE,
try_again_button = "Edit Answer",
incorrect = NULL,
rows = 3)
```
###
```{python working-with-data-12-test, echo = TRUE}
import math
x = math.sqrt(144)
```
###
The `=` symbol is the assignment operator in Python. In this case, we are *assigning* the value of `math.sqrt(144)` to the variable `x`. Nothing is printed out because of that assignment.
### Exercise 13
In the Console, run `x` or `print(x)`.
CP/CR.
```{r working-with-data-13}
question_text(NULL,
answer(NULL, correct = TRUE),
allow_retry = TRUE,
try_again_button = "Edit Answer",
incorrect = NULL,
rows = 3)
```
###
```{python working-with-data-13-test, echo = TRUE}
import math
x = math.sqrt(144)
x
```
###
Now that `x` has been defined in the Console, it is available for your use. Above, we just print it out. But we could also use it in other calculations, e.g., `x + 5`.
## Method chaining and plots
###
Although Polars includes hundreds of methods for data manipulation, the most important are `filter()`, `select()`, `sort()`, `with_columns()`, and `group_by()` with `agg()`. These work very similarly to their R tidyverse equivalents!
### Exercise 1
Let's warm up by examining the `tips` dataset. Type the following and hit "Run Code":
```
import polars as pl
tips = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv")
tips
```
```{python pipes-and-plots-1, exercise = TRUE}
```
```{python pipes-and-plots-1-hint-1, eval = FALSE}
import polars as pl
tips = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv")
...
```
```{python pipes-and-plots-1-test, include = FALSE}
import polars as pl
tips = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv")
tips
```
###
The `tips` dataset contains information about restaurant tips, including total bill, tip amount, and other variables.
### Exercise 2
Run `tips.describe()` to see summary statistics.
```{python pipes-and-plots-2, exercise = TRUE}
```
```{python pipes-and-plots-2-hint-1, eval = FALSE}
import polars as pl
tips = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv")
tips.describe()
```
```{python pipes-and-plots-2-test, include = FALSE}
import polars as pl
tips = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv")
tips.describe()
```
###
Note that this gives us statistics for the numerical columns in the dataset.
### Exercise 3
Use `.drop_nulls()` to remove rows with missing values. In Polars, we pipe operations by calling methods one after another, just like in R! Try:
```
tips.drop_nulls()
```
```{python pipes-and-plots-3, exercise = TRUE}
```
```{python pipes-and-plots-3-hint-1, eval = FALSE}
import polars as pl
tips = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv")
tips.drop_nulls()
```
```{python pipes-and-plots-3-test, include = FALSE}
import polars as pl
tips = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv")
tips.drop_nulls()
```
###
Note the number of rows in the DataFrame after `drop_nulls()`. This dataset actually has no missing values, so all rows remain.
We can chain methods by writing `tips.drop_nulls().head()` to first drop NA values and then show the first few rows.
### Exercise 4
Chain `.filter()` to filter rows. Use `pl.col("time") == "Dinner"` as the argument. This is very similar to R's `filter()`!
```{python pipes-and-plots-4, exercise = TRUE}
```
```{python pipes-and-plots-4-hint-1, eval = FALSE}
import polars as pl
tips = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv")
tips.filter(pl.col("time") == "Dinner")
```
```{python pipes-and-plots-4-test, include = FALSE}
import polars as pl
tips = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv")
tips.filter(pl.col("time") == "Dinner")
```
###
This workflow --- in which we chain DataFrame methods together --- is very common in Polars and very similar to R's pipe workflow.
The resulting DataFrame has the same number of columns as `tips` because `filter()` only affects the rows. But there are fewer rows now.
### Exercise 5
Continue the chain with `.select()` to choose specific columns. Use `["total_bill", "tip", "sex", "day"]` as the argument. You can use the "Copy Code" button to avoid retyping.
```{python pipes-and-plots-5, exercise = TRUE}
```
<button onclick = "transfer_code(this)">Copy previous code</button>
```{python pipes-and-plots-5-hint-1, eval = FALSE}
import polars as pl
tips = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv")
tips.filter(pl.col("time") == "Dinner").select(["total_bill", "tip", "sex", "day"])
```
```{python pipes-and-plots-5-test, include = FALSE}
import polars as pl
tips = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv")
tips.filter(pl.col("time") == "Dinner").select(["total_bill", "tip", "sex", "day"])
```
###
Because `select()` doesn't affect rows, we have the same number as after `filter()`. But we only have 4 columns now. This is just like R's `select()` function!
### Exercise 6
Copy previous code. Continue the chain with `.describe()`.
```{python pipes-and-plots-6, exercise = TRUE}
```
<button onclick = "transfer_code(this)">Copy previous code</button>
```{python pipes-and-plots-6-hint-1, eval = FALSE}
tips.filter(pl.col("time") == "Dinner").select(["total_bill", "tip", "sex", "day"]).describe()
```
```{python pipes-and-plots-6-test, include = FALSE}
import polars as pl
tips = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv")
tips.filter(pl.col("time") == "Dinner").select(["total_bill", "tip", "sex", "day"]).describe()
```
###
This gives us summary statistics for our filtered and selected data.
### Exercise 7
Copy previous code. Replace `.describe()` with `.drop_nulls()`.
```{python pipes-and-plots-7, exercise = TRUE}
```
<button onclick = "transfer_code(this)">Copy previous code</button>
```{python pipes-and-plots-7-hint-1, eval = FALSE}
tips.filter(pl.col("time") == "Dinner").select(["total_bill", "tip", "sex", "day"]).drop_nulls()
```
```{python pipes-and-plots-7-test, include = FALSE}
import polars as pl
tips = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv")
tips.filter(pl.col("time") == "Dinner").select(["total_bill", "tip", "sex", "day"]).drop_nulls()
```
###
The number of rows stays the same because there are no missing values in this subset.
### Exercise 8
Continue the chain with `.sort("tip")` to sort by the tip column.
```{python pipes-and-plots-8, exercise = TRUE}
```
<button onclick = "transfer_code(this)">Copy previous code</button>
```{python pipes-and-plots-8-hint-1, eval = FALSE}
tips.filter(pl.col("time") == "Dinner").select(["total_bill", "tip", "sex", "day"]).drop_nulls().sort("tip")
```
```{python pipes-and-plots-8-test, include = FALSE}
import polars as pl
tips = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv")
tips.filter(pl.col("time") == "Dinner").select(["total_bill", "tip", "sex", "day"]).drop_nulls().sort("tip")
```
###
The `sort()` method sorts the rows of a DataFrame. By default, it sorts in ascending order. This is just like R's `arrange()` function!
### Exercise 9
Copy the previous code. Add `descending=True` as an argument to `sort()` to sort in descending order. This is like using `desc()` in R!
```{python pipes-and-plots-9, exercise = TRUE}
```
<button onclick = "transfer_code(this)">Copy previous code</button>
```{python pipes-and-plots-9-hint-1, eval = FALSE}
.sort("tip", descending=True)
```
```{python pipes-and-plots-9-test, include = FALSE}
import polars as pl
tips = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv")
tips.filter(pl.col("time") == "Dinner").select(["total_bill", "tip", "sex", "day"]).drop_nulls().sort("tip", descending=True)
```
###
Got to respect someone who tips $10!
### Exercise 10
Let's make a plot! For plotting, we'll use plotnine, which works exactly like ggplot2 in R. Copy the previous code, but remove the `.sort()` line. Instead, save the result to a variable called `tips_dinner`, then convert it to pandas with `.to_pandas()` (plotnine works with pandas DataFrames), and create a plot using `ggplot()`.
Here's the pattern:
```
import polars as pl
from plotnine import ggplot, aes, geom_point
tips = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv")
tips_dinner = (tips
.filter(pl.col("time") == "Dinner")
.select(["total_bill", "tip", "sex", "day"])
.drop_nulls()
.to_pandas())
ggplot(tips_dinner, aes(x='total_bill', y='tip')) + geom_point()
```
```{python pipes-and-plots-10, exercise = TRUE}
```
<button onclick = "transfer_code(this)">Copy previous code</button>
```{python pipes-and-plots-10-hint-1, eval = FALSE}
from plotnine import ggplot, aes, geom_point
tips_dinner = (tips
.filter(pl.col("time") == "Dinner")
.select([...])
.drop_nulls()
.to_pandas())
ggplot(tips_dinner, aes(x='...', y='...')) + geom_point()
```
```{python pipes-and-plots-10-test, include = FALSE}
import polars as pl
assert 'tips' in globals(), "'tips' DataFrame not found. Run Exercise 1 first."
print("tips columns:", tips.columns)
tips_dinner_head = (tips
.filter(pl.col("time") == "Dinner")
.select(["total_bill", "tip", "sex", "day"])
.drop_nulls()
.to_pandas()
.head(5))
print("Dinner rows preview (first 5):")
print(tips_dinner_head)
```
###
This creates a scatter plot showing the relationship between total bill and tip amount. Notice how similar this is to ggplot2 in R! We use `ggplot()`, `aes()`, and `geom_point()` just like in R.
### Exercise 11
Copy previous code. Now let's add jitter to see overlapping points better, just like in R! Change `geom_point()` to `geom_jitter()`.
```{python pipes-and-plots-11, exercise = TRUE}
```
<button onclick = "transfer_code(this)">Copy previous code</button>
```{python pipes-and-plots-11-hint-1, eval = FALSE}
from plotnine import ggplot, aes, geom_jitter
ggplot(tips_dinner, aes(x='total_bill', y='tip')) + geom_jitter()
```
```{python pipes-and-plots-11-test, include = FALSE}
tips_xy = (tips
.filter(pl.col("time") == "Dinner")
.select(["total_bill", "tip"])
.drop_nulls()
.head(8))
print(tips_xy)
```
###
This is exactly like using `geom_jitter()` in R's ggplot2! The jitter adds a small amount of random noise to help us see overlapping points.
### Exercise 12
Finally, add a title and labels using `plt.title()`, `plt.xlabel()`, and `plt.ylabel()`. Consider this example:
```
import matplotlib.pyplot as plt
import seaborn as sns
tips = sns.load_dataset('tips')
tips_dinner = (tips
.query('time == "Dinner"')
[['total_bill', 'tip', 'sex', 'day']]
.dropna())
sns.scatterplot(data=tips_dinner, x='total_bill', y='tip', alpha=0.6)
plt.title('Dinner Tips vs Total Bill')
plt.xlabel('Total Bill ($)')
plt.ylabel('Tip ($)')
plt.show()
```
You can make yours look like this, or create your own title and labels.
```{python pipes-and-plots-12, exercise = TRUE}
```
<button onclick = "transfer_code(this)">Copy previous code</button>
```{python pipes-and-plots-12-hint-1, eval = FALSE}
plt.title('...')
plt.xlabel('...')
plt.ylabel('...')
plt.show()
```
```{python pipes-and-plots-12-test, include = FALSE}
tips_dinner_pd = (tips
.filter(pl.col("time") == "Dinner")
.select(["total_bill", "tip", "sex", "day"])
.drop_nulls()
.to_pandas())
print("tips_dinner shape:", tips_dinner_pd.shape)
print("columns:", list(tips_dinner_pd.columns))
```
###
Note that the code in the exercise block is not saved. If you want to save the code, you can copy/paste it into a Python script file (.py).
## Generative AI
###
Generative AI --- tools like [ChatGPT](https://chat.openai.com/), [Grok](https://x.ai/), [Claude](https://claude.ai/), [DeepSeek](https://www.deepseek.com/en) and so on --- are the future, of data science and everything else. The more you use these tools, the better off you will be. Unfortunately, the tools are changing so much that it is hard for a tutorial like this to stay up-to-date. This section provides some general advice and practice exercises.
### Exercise 1
Using any AI you like, ask it to write a one-sentence summary about the Python programming language. Copy the answer below.
```{r generative-ai-1}
question_text(NULL,
answer(NULL, correct = TRUE),
allow_retry = TRUE,
try_again_button = "Edit Answer",
incorrect = NULL,
rows = 5)
```
###
Example answer:
```
Python is a high-level, interpreted programming language known for its simplicity, readability, and versatility, widely used for web development, data analysis, artificial intelligence, and scientific computing.
```
If you do not want to pay for an AI service, then you will probably need to have free accounts with several different services. That way, if one service cuts you off for the day, you can switch to another.
### Exercise 2
Type this in the Python Console and hit Enter:
```
import polars as pl
iris = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
iris.head()
```
Copy/paste the command and the first few lines of output.
```{r generative-ai-2}
question_text(NULL,
answer(NULL, correct = TRUE),
allow_retry = TRUE,
try_again_button = "Edit Answer",
incorrect = NULL,
rows = 10)
```
###
```{python generative-ai-2-test, echo = TRUE}
import polars as pl
iris = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
iris.head()
```
When working with AI, you often need to tell it about the dataset. The easiest way to do that is often to just copy/paste the first few rows. That shows the AI what the column names and types are, which is key information for creating plots and data pipelines.
### Exercise 3
Copy/paste the top of the `iris` DataFrame into your AI interface and ask it to create a chain of methods using Polars that calculates the average `sepal_length` for each `species`. Run the provided code in the Console. If it fails, show the AI the error and ask for better code.
CP/CR.
```{r generative-ai-3}
question_text(NULL,
answer(NULL, correct = TRUE),
allow_retry = TRUE,
try_again_button = "Edit Answer",
incorrect = NULL,
rows = 10)
```
###
Claude gave us this answer:
```{python generative-ai-3-test, echo = TRUE}
import polars as pl
iris = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
iris.group_by("species").agg(pl.col("sepal_length").mean())
```
###
This is a great answer! It uses `group_by()` just like R's tidyverse, and then `agg()` (short for aggregate) with `pl.col()` to specify which column to calculate the mean for. Notice how similar this is to R:
R version: `iris |> group_by(species) |> summarize(mean_sepal_length = mean(sepal_length))`
Polars version: `iris.group_by("species").agg(pl.col("sepal_length").mean())`
Using AI is good! But intelligent use --- use in which you understand what the AI has done and try to improve/clarify its answer --- is even better.
### Exercise 4
Ask AI to create a beautiful plot using the `iris` dataset and the plotnine/seaborn libraries. Run the provided code in the Console. If it fails, show the AI the error and ask for better code.
```{r generative-ai-4}
question_text(NULL,
answer(NULL, correct = TRUE),
allow_retry = TRUE,
try_again_button = "Edit Answer",
incorrect = NULL,
rows = 20)
```
###
Example code from DeepSeek:
```{python generative-ai-4-test, echo = TRUE}
from plotnine import (
ggplot, aes, geom_point, geom_smooth,
facet_wrap, labs, theme_minimal
)
import polars as pl
# Load iris with Polars, then convert to pandas for plotnine
iris = pl.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv").to_pandas()
(
ggplot(iris, aes(x="sepal_length", y="sepal_width", color="species")) +
geom_point(size=3, alpha=0.7) +
geom_smooth(method="loess", se=False, span=0.9) +
facet_wrap("~ species") +
labs(
title="Sepal Shape Variation Across Iris Species",
x="Sepal Length (cm)",
y="Sepal Width (cm)",
color="Species"
) +
theme_minimal()
)