-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01-Fundamentals.html
1024 lines (988 loc) · 51.8 KB
/
01-Fundamentals.html
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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta charset="utf-8">
<meta name="generator" content="quarto-1.5.57">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>Fundamentals</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
width: 0.8em;
margin: 0 0.8em 0.2em -1em; /* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */
vertical-align: middle;
}
/* CSS for syntax highlighting */
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { display: inline-block; text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
}
pre.numberSource { margin-left: 3em; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script><script src="01-Fundamentals_files/libs/clipboard/clipboard.min.js"></script>
<script src="01-Fundamentals_files/libs/quarto-html/quarto.js"></script>
<script src="01-Fundamentals_files/libs/quarto-html/popper.min.js"></script>
<script src="01-Fundamentals_files/libs/quarto-html/tippy.umd.min.js"></script>
<script src="01-Fundamentals_files/libs/quarto-html/anchor.min.js"></script>
<link href="01-Fundamentals_files/libs/quarto-html/tippy.css" rel="stylesheet">
<link href="01-Fundamentals_files/libs/quarto-html/quarto-syntax-highlighting.css" rel="stylesheet" id="quarto-text-highlighting-styles">
<script src="01-Fundamentals_files/libs/bootstrap/bootstrap.min.js"></script>
<link href="01-Fundamentals_files/libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="01-Fundamentals_files/libs/bootstrap/bootstrap.min.css" rel="stylesheet" id="quarto-bootstrap" data-mode="light">
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js" integrity="sha512-c3Nl8+7g4LMSTdrm621y7kf9v3SDPnhxLNhcjFJbKECVnmZHTdo+IRO05sNLTH/D3vA6u1X32ehoLC7WFVdheg==" crossorigin="anonymous"></script>
<script type="application/javascript">define('jquery', [],function() {return window.jQuery;})</script>
</head>
<body class="fullcontent">
<div id="quarto-content" class="page-columns page-rows-contents page-layout-article">
<main class="content" id="quarto-document-content">
<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title">
<h1 class="title">Fundamentals</h1>
</div>
<div class="quarto-title-meta">
</div>
</header>
<p>Welcome to Intermediate Python! Each week, we cover a chapter, which consists of a lesson and exercise. In the first week, we go over the goals of the course, and review data structures and data types that you have seen before from <a href="https://hutchdatascience.org/Intro_to_Python/">Intro to Python</a>. We also look at some new data structures and more properties of data structures.</p>
<p>In <a href="https://hutchdatascience.org/Intro_to_Python/">Intro to Python</a>, you learned how to do basic data analysis such as subsetting a dataframe, looking at summary statistics, and visualizing your data. This was done in the context of a clean, Tidy dataframe. In this course, we focus on working with data “from the wild”, in which the data comes in a more messy, un-Tidy form. Let’s see what we will learn in the next 6 weeks together:</p>
<section id="goals-of-this-course" class="level2">
<h2 class="anchored" data-anchor-id="goals-of-this-course">Goals of this course</h2>
<ul>
<li><p>Continue building <em>programming fundamentals</em>: How to use complex data structures, create custom functions, and how to iterate repeated tasks.</p></li>
<li><p>Continue exploration of <em>data science fundamentals</em>: how to clean messy data using the programming fundamentals above to a Tidy form for analysis.</p></li>
</ul>
</section>
<section id="motivation" class="level2">
<h2 class="anchored" data-anchor-id="motivation">Motivation</h2>
<p>We will be looking at a dataset from Twitter that looks like the following:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 9%">
<col style="width: 14%">
<col style="width: 40%">
<col style="width: 9%">
<col style="width: 6%">
<col style="width: 19%">
</colgroup>
<thead>
<tr class="header">
<th>Tweet_ID</th>
<th>Username</th>
<th>Text</th>
<th>Retweets</th>
<th>Likes</th>
<th>Timestamp</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>1</td>
<td>julie81</td>
<td>Party least receive say or single….</td>
<td>2</td>
<td>25</td>
<td>2023-01-30 11:00:51</td>
</tr>
<tr class="even">
<td>2</td>
<td>richardhester</td>
<td>Hotel still Congress may member staff….</td>
<td>35</td>
<td>29</td>
<td>2023-01-02 22:45:58</td>
</tr>
<tr class="odd">
<td>3</td>
<td>williamsjoseph</td>
<td>Nice be her debate industry that year….</td>
<td>51</td>
<td>25</td>
<td>2023-01-18 11:25:19</td>
</tr>
</tbody>
</table>
<p>Suppose that we want to do some text analysis on the “Text” column: We want to assign a sentiment score (a numerical value that measures the emotional tone or attitude expressed in text) to each tweet, based on all of the words it contains. For instance, a tweet about celebrating one’s birthday will be assigned a positive sentiment score, and a tweet about getting fired from a job will be assigned a negative sentiment score.</p>
<p>If we have a function that takes in a String of words, and output a sentiment score, that would be great. However, that function does not exist in the built-in libraries of Python and Pandas, so we will have to write our custom function!</p>
<p>When we think about writing a custom function, we usually like to sketch out an outline what the function will do in English, and then try to translate it to Python code.</p>
<p>Given an input String of words,</p>
<ul>
<li><p>Examine each word in the input string:</p>
<ul>
<li><p>Associate the word with a sentiment score.</p></li>
<li><p>And keep track of this sentiment score.</p></li>
</ul></li>
<li><p>Take the average of all the sentiment scores,</p></li>
<li><p>and return it as the output.</p></li>
</ul>
<p>How do we associate a word with a sentiment score? We need another function to do that:</p>
<p>Given an input String with one word,</p>
<ul>
<li><p>Load in a “lookup dictionary” that assigns words to scores.</p></li>
<li><p>Check whether the input string is in the dictionary. Some words, such as “the”, won’t have a sentiment score.</p></li>
<li><p>If so, return the score of that word.</p></li>
</ul>
<p>Some concepts from this outline that we will learn the technical details include: writing a custom function, iterating through a data structure, and using “lookup dictionaries”. Let’s look at the Learning Objectives of the course:</p>
</section>
<section id="learning-objectives" class="level2">
<h2 class="anchored" data-anchor-id="learning-objectives">Learning Objectives</h2>
<ul>
<li><p><strong>Distinguish</strong> the use cases of common data structures, such as Lists, Dictionaries, and Series.</p></li>
<li><p><strong>Recognize</strong> and <strong>describe</strong> common iteration patterns on common data structures, such as counting and searching.</p></li>
<li><p><strong>Implement</strong> “iterable” operations, including For-Loops and List Comprehensions, on data structures that can be iterated (Lists, Dictionaries, Series, and even Strings).</p></li>
<li><p><strong>Implement</strong> conditional statements when the program logic requires a branching structure.</p></li>
<li><p><strong>Create</strong> simple, modular functions, including anonymous functions, that can be reused.</p></li>
<li><p><strong>Describe</strong> the difference between copying an object vs. referencing an object and how that could affect variables in a data analysis.</p></li>
</ul>
</section>
<section id="data-types-in-python" class="level2">
<h2 class="anchored" data-anchor-id="data-types-in-python">Data types in Python</h2>
<p>To get started, let’s recall the fundamental data types in Python:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Data type name</th>
<th style="text-align: center;"><strong>Data type shorthand</strong></th>
<th style="text-align: center;"><strong>Examples</strong></th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Integer</td>
<td style="text-align: center;">int</td>
<td style="text-align: center;">2, 4</td>
</tr>
<tr class="even">
<td>Float</td>
<td style="text-align: center;">float</td>
<td style="text-align: center;">3.5, -34.1009</td>
</tr>
<tr class="odd">
<td>String</td>
<td style="text-align: center;">str</td>
<td style="text-align: center;">“hello”, “234-234-8594”</td>
</tr>
<tr class="even">
<td>Boolean</td>
<td style="text-align: center;">bool</td>
<td style="text-align: center;">True, False</td>
</tr>
</tbody>
</table>
<p>There’s a special data type called <code>None</code> in Python, in which is used as a placeholder. We will talk about it later this course.</p>
</section>
<section id="data-structures" class="level2">
<h2 class="anchored" data-anchor-id="data-structures">Data Structures</h2>
<p>And fundamental data structures:</p>
<ul>
<li><p>List</p></li>
<li><p>Dataframe</p></li>
<li><p>Series</p></li>
<li><p><strong>Dictionary</strong></p></li>
<li><p><strong>Tuple</strong></p></li>
</ul>
<p>We will look at our new data structure, the Dictionary, carefully today. You will learn a little bit about Tuples in your exercise.</p>
</section>
<section id="objects-in-python" class="level2">
<h2 class="anchored" data-anchor-id="objects-in-python">Objects in Python</h2>
<p>All of our Data Structures are organized under the Objects framework in Python. For each data structure type, we can examine:</p>
<ul>
<li><p>What does it contain (in terms of data)?</p></li>
<li><p>What can it do (in terms of functions)?</p></li>
</ul>
<p>And if it “makes sense” to us, then it is well-designed Object.</p>
<p>Formally, an <strong>object</strong> contains the following:</p>
<ul>
<li><p><strong>Value</strong> that holds the essential data for the object.</p></li>
<li><p><strong>Attributes</strong> that hold subset or additional data for the object.</p></li>
<li><p>Functions called <strong>Methods</strong> that are for the object and <em>have to</em> take in the variable referenced as an input.</p></li>
</ul>
<p>This organizing structure on an object applies to pretty much all Python data types and data structures.</p>
<p>Let’s see how this applies to the Dataframe:</p>
<p>Suppose we have the following Dataframe:</p>
<div id="ddb7b8e0" class="cell" data-execution_count="1">
<div class="sourceCode cell-code" id="cb1"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> pandas <span class="im">as</span> pd</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>simple_df <span class="op">=</span> pd.DataFrame(data<span class="op">=</span>{<span class="st">'id'</span>: [<span class="st">"AAA"</span>, <span class="st">"BBB"</span>, <span class="st">"CCC"</span>, <span class="st">"DDD"</span>, <span class="st">"EEE"</span>],</span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a> <span class="st">'case_control'</span>: [<span class="st">"case"</span>, <span class="st">"case"</span>, <span class="st">"control"</span>, <span class="st">"control"</span>, <span class="st">"control"</span>],</span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a> <span class="st">'measurement1'</span>: [<span class="fl">2.5</span>, <span class="fl">3.5</span>, <span class="dv">9</span>, <span class="fl">.1</span>, <span class="fl">2.2</span>],</span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a> <span class="st">'measurement2'</span>: [<span class="dv">0</span>, <span class="dv">0</span>, <span class="fl">.5</span>, <span class="fl">.24</span>, <span class="fl">.003</span>],</span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a> <span class="st">'measurement3'</span>: [<span class="dv">80</span>, <span class="dv">2</span>, <span class="dv">1</span>, <span class="dv">1</span>, <span class="dv">2</span>]})</span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a>simple_df</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="1">
<div>
<table class="dataframe caption-top table table-sm table-striped small" data-quarto-postprocess="true" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">id</th>
<th data-quarto-table-cell-role="th">case_control</th>
<th data-quarto-table-cell-role="th">measurement1</th>
<th data-quarto-table-cell-role="th">measurement2</th>
<th data-quarto-table-cell-role="th">measurement3</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td data-quarto-table-cell-role="th">0</td>
<td>AAA</td>
<td>case</td>
<td>2.5</td>
<td>0.000</td>
<td>80</td>
</tr>
<tr class="even">
<td data-quarto-table-cell-role="th">1</td>
<td>BBB</td>
<td>case</td>
<td>3.5</td>
<td>0.000</td>
<td>2</td>
</tr>
<tr class="odd">
<td data-quarto-table-cell-role="th">2</td>
<td>CCC</td>
<td>control</td>
<td>9.0</td>
<td>0.500</td>
<td>1</td>
</tr>
<tr class="even">
<td data-quarto-table-cell-role="th">3</td>
<td>DDD</td>
<td>control</td>
<td>0.1</td>
<td>0.240</td>
<td>1</td>
</tr>
<tr class="odd">
<td data-quarto-table-cell-role="th">4</td>
<td>EEE</td>
<td>control</td>
<td>2.2</td>
<td>0.003</td>
<td>2</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<ul>
<li><p><strong>Value</strong>: the contents of the Dataframe, which is a tabular data format in columns and rows.</p></li>
<li><p><strong>Attributes</strong> that allow one to access subset of the data or additional data:</p>
<ul>
<li><p><code>simple_df.id</code> access the column “id”, returning a Series object.</p></li>
<li><p><code>simple_df.shape</code> access the the number of rows and columns.</p></li>
<li><p>Subsetting via the bracket <code>.iloc[row_idx, col_idx]</code> or <code>.loc[row_idx, col_idx]</code> notation.</p></li>
</ul></li>
<li><p><strong>Methods</strong> that can be used on the object:</p>
<ul>
<li><p><code>simple_df.head()</code> and <code>simple_df.tail()</code> access the first and last few elements of the Dataframe, respectively.</p></li>
<li><p><code>simple_df.merge(another_df)</code> merges <code>simple_df</code> with another Dataframe <code>another_df</code>.</p></li>
</ul></li>
</ul>
<p>We have some of our favorite attributes and methods of Dataframes <a href="https://docs.google.com/document/d/1si-4suESej1Vjopkv5KiI-hGylXk11osmO3oEfpYOuc/edit?tab=t.0">from Intro to Python here</a>.</p>
</section>
<section id="dictionary" class="level2">
<h2 class="anchored" data-anchor-id="dictionary">Dictionary</h2>
<p>Today, we will introduce a new data structure, called the <strong>Dictionary</strong>. A dictionary is designed as a lookup table, organized in <strong>key-value</strong> pairs. You associate the key with a particular value, and use the key to find the value. You should consider using a dictionary when you are storing a collection of associations. Another way of saying this is that dictionaries are useful for storing and manipulating correspondence relationships.</p>
<p>For instance, suppose that we want to associate common English words with a sentiment value:</p>
<div id="29e7b66a" class="cell" data-execution_count="2">
<div class="sourceCode cell-code" id="cb2"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>sentiment <span class="op">=</span> {<span class="st">'happy'</span>: <span class="dv">8</span>, <span class="st">'sad'</span>: <span class="dv">2</span>, <span class="st">'joy'</span>: <span class="fl">7.5</span>, <span class="st">'embarrassed'</span>: <span class="fl">3.6</span>, <span class="st">'restless'</span>: <span class="fl">4.1</span>, <span class="st">'apathetic'</span>: <span class="fl">3.8</span>, <span class="st">'calm'</span>: <span class="dv">7</span>}</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>sentiment</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="2">
<pre><code>{'happy': 8,
'sad': 2,
'joy': 7.5,
'embarrassed': 3.6,
'restless': 4.1,
'apathetic': 3.8,
'calm': 7}</code></pre>
</div>
</div>
<p>If we want to find the sentiment value of a word, we can look it up immediately via its key to access its value:</p>
<div id="0e1cc253" class="cell" data-execution_count="3">
<div class="sourceCode cell-code" id="cb4"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a>sentiment[<span class="st">'joy'</span>]</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="3">
<pre><code>7.5</code></pre>
</div>
</div>
<p>However, we cannot access the nth element of a Dictionary, as we are able to do with Lists and Series:</p>
<div id="b1afffcd" class="cell" data-execution_count="4">
<div class="sourceCode cell-code" id="cb6"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="co">#sentiment[0] error!</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>If we didn’t have a tool such as Dictionary, we could have tried to implement the following via Pandas Dataframes:</p>
<div id="1561ca82" class="cell" data-execution_count="5">
<div class="sourceCode cell-code" id="cb7"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a>sentiment_df <span class="op">=</span> pd.DataFrame(data<span class="op">=</span>{<span class="st">'word'</span>: [<span class="st">"happy"</span>, <span class="st">"sad"</span>, <span class="st">"joy"</span>, <span class="st">"embarrassed"</span>, <span class="st">"restless"</span>, <span class="st">"apathetic"</span>, <span class="st">"calm"</span>],</span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a> <span class="st">'sentiment'</span>: [<span class="dv">8</span>, <span class="dv">2</span>, <span class="fl">7.5</span>, <span class="fl">3.6</span>, <span class="fl">4.1</span>, <span class="fl">3.8</span>, <span class="dv">7</span>]})</span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a>sentiment_df</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="5">
<div>
<table class="dataframe caption-top table table-sm table-striped small" data-quarto-postprocess="true" data-border="1">
<thead>
<tr class="header">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">word</th>
<th data-quarto-table-cell-role="th">sentiment</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td data-quarto-table-cell-role="th">0</td>
<td>happy</td>
<td>8.0</td>
</tr>
<tr class="even">
<td data-quarto-table-cell-role="th">1</td>
<td>sad</td>
<td>2.0</td>
</tr>
<tr class="odd">
<td data-quarto-table-cell-role="th">2</td>
<td>joy</td>
<td>7.5</td>
</tr>
<tr class="even">
<td data-quarto-table-cell-role="th">3</td>
<td>embarrassed</td>
<td>3.6</td>
</tr>
<tr class="odd">
<td data-quarto-table-cell-role="th">4</td>
<td>restless</td>
<td>4.1</td>
</tr>
<tr class="even">
<td data-quarto-table-cell-role="th">5</td>
<td>apathetic</td>
<td>3.8</td>
</tr>
<tr class="odd">
<td data-quarto-table-cell-role="th">6</td>
<td>calm</td>
<td>7.0</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>But to access a word’s sentiment value, you have to write a complex syntax:</p>
<div id="7ee4422c" class="cell" data-execution_count="6">
<div class="sourceCode cell-code" id="cb8"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a>sentiment_df.loc[sentiment_df.word <span class="op">==</span> <span class="st">"joy"</span>, <span class="st">"sentiment"</span>]</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="6">
<pre><code>2 7.5
Name: sentiment, dtype: float64</code></pre>
</div>
</div>
<p>Besides the cumbersome syntax, it is not very fast: the program has to find which row “joy” is at. Whereas, in the dictionary data structure, the lookup is immediate. The time it takes for dictionary to take a key and retrieve a value <em>does not depend on the size of the dictionary,</em> whereas it does for the Dataframe implementation.</p>
<section id="basic-rules-of-dictionaries" class="level3">
<h3 class="anchored" data-anchor-id="basic-rules-of-dictionaries">Basic Rules of Dictionaries</h3>
<p>Here are some basic usage rules of Dictionaries:</p>
<ul>
<li><p>Only one value per key. No duplicate keys allowed.</p></li>
<li><p><strong>Keys</strong> must be of string, integer, float, boolean, or tuple.</p></li>
<li><p><strong>Values</strong> can be of any type, including data structures such as lists and dictionaries.</p></li>
</ul>
<p>If duplicated keys are given, then the last unique key is kept.</p>
<pre class="{hon}"><code>duplicated_keys = {'Student' : 97, 'Student': 88, 'Student' : 91}
duplicated_keys</code></pre>
<p>It is quite common to have data structures within a dictionary. Notice that when we create a Dataframe from scratch, we give it a dictionary, where the column names are keys and columns are values. A Dataframe is built on top of a dictionary with more tools!</p>
</section>
<section id="basic-usage-of-dictionaries" class="level3">
<h3 class="anchored" data-anchor-id="basic-usage-of-dictionaries">Basic Usage of Dictionaries</h3>
<p>You can modify values of a corresponding key in a dictionary:</p>
<div id="44fd00ef" class="cell" data-execution_count="7">
<div class="sourceCode cell-code" id="cb11"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a>sentiment[<span class="st">'joy'</span>] <span class="op">=</span> sentiment[<span class="st">'joy'</span>] <span class="op">+</span> <span class="dv">1</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>You will get an error if you try to access a key that doesn’t exist:</p>
<div id="0e1cb5ac" class="cell" data-execution_count="8">
<div class="sourceCode cell-code" id="cb12"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="co">#sentiment['dog']</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Alternatively, if you don’t want to run the risk of getting an error, you can specify a default value using the <code>.get()</code> method. Here, we give a default neutral value of 5 if the key doesn’t exist.</p>
<div id="e3a5c3bc" class="cell" data-execution_count="9">
<div class="sourceCode cell-code" id="cb13"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a>sentiment.get(<span class="st">"dog"</span>, <span class="dv">5</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="9">
<pre><code>5</code></pre>
</div>
</div>
<p>If you don’t specify a default value, and the key does not exist, you will get a special <code>None</code> data type.</p>
<div id="de89e7f9" class="cell" data-execution_count="10">
<div class="sourceCode cell-code" id="cb15"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(sentiment.get(<span class="st">"dog"</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>None</code></pre>
</div>
</div>
<p>You can add more key-value pairs via <code>my_dict[new_key] = new_value</code> syntax. If the key already exists, the mapping for that key will simply be updated.</p>
<div id="03885ac4" class="cell" data-execution_count="11">
<div class="sourceCode cell-code" id="cb17"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a>sentiment[<span class="st">'dog'</span>] <span class="op">=</span> <span class="dv">5</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="application-for-data-cleaning" class="level3">
<h3 class="anchored" data-anchor-id="application-for-data-cleaning">Application for Data Cleaning</h3>
<p>Suppose that you want to do some data recoding. You want to look at the “case_control” column of <code>simple_df</code> and change “case” to “experiment” and “control” to “baseline”. This correspondence relationship can be stored in a dictionary. You can use the <code>.replace()</code> method for Series objects with a dictionary as an input argument.</p>
<div id="9969d9cd" class="cell" data-execution_count="12">
<div class="sourceCode cell-code" id="cb18"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a>simple_df.case_control.replace({<span class="st">"case"</span>: <span class="st">"experiment"</span>, <span class="st">"control"</span>: <span class="st">"baseline"</span>})</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="12">
<pre><code>0 experiment
1 experiment
2 baseline
3 baseline
4 baseline
Name: case_control, dtype: object</code></pre>
</div>
</div>
</section>
</section>
<section id="converting-between-data-types" class="level2">
<h2 class="anchored" data-anchor-id="converting-between-data-types">Converting between data types</h2>
<p>Often, we need to convert between data types and data structures. You should consider whether the conversion is:</p>
<ol type="1">
<li>Permissible</li>
<li>Whether any information will be lost</li>
</ol>
<section id="data-types" class="level3">
<h3 class="anchored" data-anchor-id="data-types">Data types</h3>
<p>You can convert any number to a String.</p>
<div id="ae506f6c" class="cell" data-execution_count="13">
<div class="sourceCode cell-code" id="cb20"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a>age <span class="op">=</span> <span class="fl">24.5</span></span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a><span class="bu">str</span>(age)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="13">
<pre><code>'24.5'</code></pre>
</div>
</div>
<p>Let’s try to convert a String to a Float:</p>
<div id="8651c959" class="cell" data-execution_count="14">
<div class="sourceCode cell-code" id="cb22"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a>age <span class="op">=</span> <span class="st">"24.5"</span></span>
<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a><span class="bu">float</span>(age)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="14">
<pre><code>24.5</code></pre>
</div>
</div>
<p>But it is not permissible to convert to an Integer, as we don’t know what to do with the decimals (we comment out code that will error, so that this page will render).</p>
<div id="97ba863a" class="cell" data-execution_count="15">
<div class="sourceCode cell-code" id="cb24"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a><span class="co">#int(age) returns an error</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>And we cannot convert some Strings to any number.</p>
<div id="928dfc28" class="cell" data-execution_count="16">
<div class="sourceCode cell-code" id="cb25"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a>car <span class="op">=</span> <span class="st">"prius"</span></span>
<span id="cb25-2"><a href="#cb25-2" aria-hidden="true" tabindex="-1"></a><span class="co">#float(prius) returns an error</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Sometimes, we need to pay attention whether any information is lost in the conversion. Let’s convert Float to Int:</p>
<div id="5f2a225c" class="cell" data-execution_count="17">
<div class="sourceCode cell-code" id="cb26"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb26-1"><a href="#cb26-1" aria-hidden="true" tabindex="-1"></a>temperature <span class="op">=</span> <span class="fl">98.6</span></span>
<span id="cb26-2"><a href="#cb26-2" aria-hidden="true" tabindex="-1"></a><span class="bu">int</span>(temperature)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="17">
<pre><code>98</code></pre>
</div>
</div>
<p>Notice that the conversion dropped the decimal point entirely.</p>
</section>
</section>
<section id="converting-between-data-structures" class="level2">
<h2 class="anchored" data-anchor-id="converting-between-data-structures">Converting between data structures</h2>
<p>When we look at a column, it is of the Series data structure.</p>
<div id="0d4f17f4" class="cell" data-execution_count="18">
<div class="sourceCode cell-code" id="cb28"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb28-1"><a href="#cb28-1" aria-hidden="true" tabindex="-1"></a>simple_df[<span class="st">'measurement1'</span>]</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="18">
<pre><code>0 2.5
1 3.5
2 9.0
3 0.1
4 2.2
Name: measurement1, dtype: float64</code></pre>
</div>
</div>
<p>Let’s convert it to a List:</p>
<div id="fcf42766" class="cell" data-execution_count="19">
<div class="sourceCode cell-code" id="cb30"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb30-1"><a href="#cb30-1" aria-hidden="true" tabindex="-1"></a>simple_df[<span class="st">'measurement1'</span>].to_list()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="19">
<pre><code>[2.5, 3.5, 9.0, 0.1, 2.2]</code></pre>
</div>
</div>
<p>If you look at the <a href="https://pandas.pydata.org/docs/reference/series.html">documentation of Series</a>, there’s a lot of other conversions you can do, in the <code>.to_*()</code> methods, such as <code>.to_string()</code>.</p>
<p>When making these conversions, you might ask why isn’t the column of a Dataframe just a List instead of a Series. The answer is that there are useful values, attributes, and methods about a Series that are more useful for data analysis compared to a List. You can compute <code>.mean()</code> to get the average value of a Series or <code>.plot()</code> to make a simple plot, but these methods doe not exist for a List. Series are also designed to compute on large datasets more efficiently than Lists. However, Lists can store elements from various data types, and can store Lists within Lists. When we make conversions, we think about what data structure is more appropriate than the other, which is a big theme of this course!</p>
</section>
<section id="is-my-variable-a-data-typestructure" class="level2">
<h2 class="anchored" data-anchor-id="is-my-variable-a-data-typestructure">Is my variable a data type/structure?</h2>
<p>Often, you need to check whether your variable is a specific data type or structure. From Intro to Python, you learned about the <code>type()</code> function, such as:</p>
<div id="e2f468f3" class="cell" data-execution_count="20">
<div class="sourceCode cell-code" id="cb32"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb32-1"><a href="#cb32-1" aria-hidden="true" tabindex="-1"></a><span class="bu">type</span>(simple_df)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="20">
<pre><code>pandas.core.frame.DataFrame</code></pre>
</div>
</div>
<p>This is great, but the output of <code>type()</code> can be rather verbose, and is usually useful for printing and testing scenarios. To have a more concise, robust way of checking, we prefer the <code>isinstance()</code> function:</p>
<div id="60cfec1f" class="cell" data-execution_count="21">
<div class="sourceCode cell-code" id="cb34"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb34-1"><a href="#cb34-1" aria-hidden="true" tabindex="-1"></a><span class="bu">isinstance</span>(simple_df, pd.DataFrame)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="21">
<pre><code>True</code></pre>
</div>
</div>
<p>This directly reference the Object’s type, which is more clear.</p>
<div id="3a04ec98" class="cell" data-execution_count="22">
<div class="sourceCode cell-code" id="cb36"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb36-1"><a href="#cb36-1" aria-hidden="true" tabindex="-1"></a><span class="bu">isinstance</span>(simple_df, <span class="bu">list</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="22">
<pre><code>False</code></pre>
</div>
</div>
</section>
<section id="exercises" class="level2">
<h2 class="anchored" data-anchor-id="exercises">Exercises</h2>
<p>Exercise for week 1 can be found <a href="https://colab.research.google.com/drive/1nskVV4XFDVjkN_6OIQJDtDettOEr-n5W?usp=sharing">here</a>.</p>
</section>
</main>
<!-- /main column -->
<script id="quarto-html-after-body" type="application/javascript">
window.document.addEventListener("DOMContentLoaded", function (event) {
const toggleBodyColorMode = (bsSheetEl) => {
const mode = bsSheetEl.getAttribute("data-mode");
const bodyEl = window.document.querySelector("body");
if (mode === "dark") {
bodyEl.classList.add("quarto-dark");
bodyEl.classList.remove("quarto-light");
} else {
bodyEl.classList.add("quarto-light");
bodyEl.classList.remove("quarto-dark");
}
}
const toggleBodyColorPrimary = () => {
const bsSheetEl = window.document.querySelector("link#quarto-bootstrap");
if (bsSheetEl) {
toggleBodyColorMode(bsSheetEl);
}
}
toggleBodyColorPrimary();
const icon = "";
const anchorJS = new window.AnchorJS();
anchorJS.options = {
placement: 'right',
icon: icon
};
anchorJS.add('.anchored');
const isCodeAnnotation = (el) => {
for (const clz of el.classList) {
if (clz.startsWith('code-annotation-')) {
return true;
}
}
return false;
}
const onCopySuccess = function(e) {
// button target
const button = e.trigger;
// don't keep focus
button.blur();
// flash "checked"
button.classList.add('code-copy-button-checked');
var currentTitle = button.getAttribute("title");
button.setAttribute("title", "Copied!");
let tooltip;
if (window.bootstrap) {
button.setAttribute("data-bs-toggle", "tooltip");
button.setAttribute("data-bs-placement", "left");
button.setAttribute("data-bs-title", "Copied!");
tooltip = new bootstrap.Tooltip(button,
{ trigger: "manual",
customClass: "code-copy-button-tooltip",
offset: [0, -8]});
tooltip.show();
}
setTimeout(function() {
if (tooltip) {
tooltip.hide();
button.removeAttribute("data-bs-title");
button.removeAttribute("data-bs-toggle");
button.removeAttribute("data-bs-placement");
}
button.setAttribute("title", currentTitle);
button.classList.remove('code-copy-button-checked');
}, 1000);
// clear code selection
e.clearSelection();
}
const getTextToCopy = function(trigger) {
const codeEl = trigger.previousElementSibling.cloneNode(true);
for (const childEl of codeEl.children) {
if (isCodeAnnotation(childEl)) {
childEl.remove();
}
}
return codeEl.innerText;
}
const clipboard = new window.ClipboardJS('.code-copy-button:not([data-in-quarto-modal])', {
text: getTextToCopy
});
clipboard.on('success', onCopySuccess);
if (window.document.getElementById('quarto-embedded-source-code-modal')) {
// For code content inside modals, clipBoardJS needs to be initialized with a container option
// TODO: Check when it could be a function (https://github.com/zenorocha/clipboard.js/issues/860)
const clipboardModal = new window.ClipboardJS('.code-copy-button[data-in-quarto-modal]', {
text: getTextToCopy,
container: window.document.getElementById('quarto-embedded-source-code-modal')
});
clipboardModal.on('success', onCopySuccess);
}
var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//);
var mailtoRegex = new RegExp(/^mailto:/);
var filterRegex = new RegExp('/' + window.location.host + '/');
var isInternal = (href) => {
return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href);
}
// Inspect non-navigation links and adorn them if external
var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool):not(.about-link)');
for (var i=0; i<links.length; i++) {
const link = links[i];
if (!isInternal(link.href)) {
// undo the damage that might have been done by quarto-nav.js in the case of
// links that we want to consider external
if (link.dataset.originalHref !== undefined) {
link.href = link.dataset.originalHref;
}
}
}
function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) {
const config = {
allowHTML: true,
maxWidth: 500,
delay: 100,
arrow: false,
appendTo: function(el) {
return el.parentElement;
},
interactive: true,
interactiveBorder: 10,
theme: 'quarto',
placement: 'bottom-start',
};
if (contentFn) {
config.content = contentFn;
}
if (onTriggerFn) {
config.onTrigger = onTriggerFn;
}
if (onUntriggerFn) {
config.onUntrigger = onUntriggerFn;
}
window.tippy(el, config);
}
const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]');
for (var i=0; i<noterefs.length; i++) {
const ref = noterefs[i];
tippyHover(ref, function() {
// use id or data attribute instead here
let href = ref.getAttribute('data-footnote-href') || ref.getAttribute('href');
try { href = new URL(href).hash; } catch {}
const id = href.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note) {
return note.innerHTML;
} else {
return "";
}
});
}
const xrefs = window.document.querySelectorAll('a.quarto-xref');
const processXRef = (id, note) => {
// Strip column container classes
const stripColumnClz = (el) => {
el.classList.remove("page-full", "page-columns");
if (el.children) {
for (const child of el.children) {
stripColumnClz(child);
}
}
}
stripColumnClz(note)
if (id === null || id.startsWith('sec-')) {
// Special case sections, only their first couple elements
const container = document.createElement("div");
if (note.children && note.children.length > 2) {
container.appendChild(note.children[0].cloneNode(true));
for (let i = 1; i < note.children.length; i++) {
const child = note.children[i];
if (child.tagName === "P" && child.innerText === "") {
continue;
} else {
container.appendChild(child.cloneNode(true));
break;
}
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(container);
}
return container.innerHTML
} else {
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
return note.innerHTML;
}
} else {
// Remove any anchor links if they are present
const anchorLink = note.querySelector('a.anchorjs-link');
if (anchorLink) {
anchorLink.remove();
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
// TODO in 1.5, we should make sure this works without a callout special case
if (note.classList.contains("callout")) {
return note.outerHTML;
} else {
return note.innerHTML;
}
}
}
for (var i=0; i<xrefs.length; i++) {
const xref = xrefs[i];
tippyHover(xref, undefined, function(instance) {
instance.disable();
let url = xref.getAttribute('href');
let hash = undefined;
if (url.startsWith('#')) {
hash = url;
} else {
try { hash = new URL(url).hash; } catch {}
}
if (hash) {
const id = hash.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note !== null) {
try {
const html = processXRef(id, note.cloneNode(true));
instance.setContent(html);
} finally {
instance.enable();
instance.show();
}
} else {
// See if we can fetch this
fetch(url.split('#')[0])
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.getElementById(id);
if (note !== null) {
const html = processXRef(id, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
} else {
// See if we can fetch a full url (with no hash to target)
// This is a special case and we should probably do some content thinning / targeting
fetch(url)
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.querySelector('main.content');
if (note !== null) {
// This should only happen for chapter cross references
// (since there is no id in the URL)
// remove the first header
if (note.children.length > 0 && note.children[0].tagName === "HEADER") {
note.children[0].remove();
}
const html = processXRef(null, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
}, function(instance) {
});
}
let selectedAnnoteEl;
const selectorForAnnotation = ( cell, annotation) => {
let cellAttr = 'data-code-cell="' + cell + '"';
let lineAttr = 'data-code-annotation="' + annotation + '"';
const selector = 'span[' + cellAttr + '][' + lineAttr + ']';
return selector;
}
const selectCodeLines = (annoteEl) => {
const doc = window.document;
const targetCell = annoteEl.getAttribute("data-target-cell");
const targetAnnotation = annoteEl.getAttribute("data-target-annotation");
const annoteSpan = window.document.querySelector(selectorForAnnotation(targetCell, targetAnnotation));
const lines = annoteSpan.getAttribute("data-code-lines").split(",");
const lineIds = lines.map((line) => {
return targetCell + "-" + line;
})
let top = null;
let height = null;
let parent = null;
if (lineIds.length > 0) {
//compute the position of the single el (top and bottom and make a div)
const el = window.document.getElementById(lineIds[0]);
top = el.offsetTop;
height = el.offsetHeight;
parent = el.parentElement.parentElement;
if (lineIds.length > 1) {
const lastEl = window.document.getElementById(lineIds[lineIds.length - 1]);
const bottom = lastEl.offsetTop + lastEl.offsetHeight;
height = bottom - top;
}
if (top !== null && height !== null && parent !== null) {
// cook up a div (if necessary) and position it
let div = window.document.getElementById("code-annotation-line-highlight");
if (div === null) {
div = window.document.createElement("div");
div.setAttribute("id", "code-annotation-line-highlight");
div.style.position = 'absolute';
parent.appendChild(div);
}
div.style.top = top - 2 + "px";
div.style.height = height + 4 + "px";
div.style.left = 0;
let gutterDiv = window.document.getElementById("code-annotation-line-highlight-gutter");
if (gutterDiv === null) {
gutterDiv = window.document.createElement("div");
gutterDiv.setAttribute("id", "code-annotation-line-highlight-gutter");
gutterDiv.style.position = 'absolute';
const codeCell = window.document.getElementById(targetCell);
const gutter = codeCell.querySelector('.code-annotation-gutter');
gutter.appendChild(gutterDiv);
}
gutterDiv.style.top = top - 2 + "px";
gutterDiv.style.height = height + 4 + "px";
}
selectedAnnoteEl = annoteEl;
}
};
const unselectCodeLines = () => {
const elementsIds = ["code-annotation-line-highlight", "code-annotation-line-highlight-gutter"];
elementsIds.forEach((elId) => {
const div = window.document.getElementById(elId);
if (div) {
div.remove();
}
});
selectedAnnoteEl = undefined;
};
// Handle positioning of the toggle
window.addEventListener(
"resize",
throttle(() => {
elRect = undefined;
if (selectedAnnoteEl) {
selectCodeLines(selectedAnnoteEl);
}
}, 10)
);
function throttle(fn, ms) {
let throttle = false;
let timer;
return (...args) => {
if(!throttle) { // first call gets through
fn.apply(this, args);
throttle = true;
} else { // all the others get throttled
if(timer) clearTimeout(timer); // cancel #2
timer = setTimeout(() => {
fn.apply(this, args);
timer = throttle = false;
}, ms);
}
};
}
// Attach click handler to the DT
const annoteDls = window.document.querySelectorAll('dt[data-target-cell]');
for (const annoteDlNode of annoteDls) {
annoteDlNode.addEventListener('click', (event) => {
const clickedEl = event.target;
if (clickedEl !== selectedAnnoteEl) {
unselectCodeLines();
const activeEl = window.document.querySelector('dt[data-target-cell].code-annotation-active');
if (activeEl) {
activeEl.classList.remove('code-annotation-active');
}
selectCodeLines(clickedEl);
clickedEl.classList.add('code-annotation-active');
} else {
// Unselect the line
unselectCodeLines();
clickedEl.classList.remove('code-annotation-active');
}
});
}
const findCites = (el) => {
const parentEl = el.parentElement;
if (parentEl) {
const cites = parentEl.dataset.cites;
if (cites) {
return {
el,
cites: cites.split(' ')
};
} else {
return findCites(el.parentElement)
}
} else {
return undefined;
}
};
var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]');
for (var i=0; i<bibliorefs.length; i++) {
const ref = bibliorefs[i];
const citeInfo = findCites(ref);
if (citeInfo) {