-
Notifications
You must be signed in to change notification settings - Fork 0
/
index 2.tex
8734 lines (7256 loc) · 365 KB
/
index 2.tex
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
% Options for packages loaded elsewhere
\PassOptionsToPackage{unicode}{hyperref}
\PassOptionsToPackage{hyphens}{url}
\PassOptionsToPackage{dvipsnames,svgnames,x11names}{xcolor}
%
\documentclass[
letterpaper,
DIV=11,
numbers=noendperiod]{scrreprt}
\usepackage{amsmath,amssymb}
\usepackage{lmodern}
\usepackage{iftex}
\ifPDFTeX
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{textcomp} % provide euro and other symbols
\else % if luatex or xetex
\usepackage{unicode-math}
\defaultfontfeatures{Scale=MatchLowercase}
\defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
\fi
% Use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\IfFileExists{microtype.sty}{% use microtype if available
\usepackage[]{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\makeatletter
\@ifundefined{KOMAClassName}{% if non-KOMA class
\IfFileExists{parskip.sty}{%
\usepackage{parskip}
}{% else
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}}
}{% if KOMA class
\KOMAoptions{parskip=half}}
\makeatother
\usepackage{xcolor}
\setlength{\emergencystretch}{3em} % prevent overfull lines
\setcounter{secnumdepth}{5}
% Make \paragraph and \subparagraph free-standing
\ifx\paragraph\undefined\else
\let\oldparagraph\paragraph
\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
\fi
\ifx\subparagraph\undefined\else
\let\oldsubparagraph\subparagraph
\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
\fi
\usepackage{color}
\usepackage{fancyvrb}
\newcommand{\VerbBar}{|}
\newcommand{\VERB}{\Verb[commandchars=\\\{\}]}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
% Add ',fontsize=\small' for more characters per line
\usepackage{framed}
\definecolor{shadecolor}{RGB}{241,243,245}
\newenvironment{Shaded}{\begin{snugshade}}{\end{snugshade}}
\newcommand{\AlertTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{#1}}
\newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.40,0.45,0.13}{#1}}
\newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\BuiltInTok}[1]{\textcolor[rgb]{0.00,0.23,0.31}{#1}}
\newcommand{\CharTok}[1]{\textcolor[rgb]{0.13,0.47,0.30}{#1}}
\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{#1}}
\newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{\textit{#1}}}
\newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{#1}}
\newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.00,0.23,0.31}{#1}}
\newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{\textit{#1}}}
\newcommand{\ErrorTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\ExtensionTok}[1]{\textcolor[rgb]{0.00,0.23,0.31}{#1}}
\newcommand{\FloatTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.28,0.35,0.67}{#1}}
\newcommand{\ImportTok}[1]{\textcolor[rgb]{0.00,0.46,0.62}{#1}}
\newcommand{\InformationTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{#1}}
\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.00,0.23,0.31}{#1}}
\newcommand{\NormalTok}[1]{\textcolor[rgb]{0.00,0.23,0.31}{#1}}
\newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{#1}}
\newcommand{\OtherTok}[1]{\textcolor[rgb]{0.00,0.23,0.31}{#1}}
\newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\RegionMarkerTok}[1]{\textcolor[rgb]{0.00,0.23,0.31}{#1}}
\newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{#1}}
\newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.13,0.47,0.30}{#1}}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.13,0.47,0.30}{#1}}
\newcommand{\VariableTok}[1]{\textcolor[rgb]{0.07,0.07,0.07}{#1}}
\newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.13,0.47,0.30}{#1}}
\newcommand{\WarningTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{\textit{#1}}}
\providecommand{\tightlist}{%
\setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}\usepackage{longtable,booktabs,array}
\usepackage{calc} % for calculating minipage widths
% Correct order of tables after \paragraph or \subparagraph
\usepackage{etoolbox}
\makeatletter
\patchcmd\longtable{\par}{\if@noskipsec\mbox{}\fi\par}{}{}
\makeatother
% Allow footnotes in longtable head/foot
\IfFileExists{footnotehyper.sty}{\usepackage{footnotehyper}}{\usepackage{footnote}}
\makesavenoteenv{longtable}
\usepackage{graphicx}
\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
\def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi}
\makeatother
% Scale images if necessary, so that they will not overflow the page
% margins by default, and it is still possible to overwrite the defaults
% using explicit options in \includegraphics[width, height, ...]{}
\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
% Set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother
\KOMAoption{captions}{tableheading}
\makeatletter
\@ifpackageloaded{tcolorbox}{}{\usepackage[many]{tcolorbox}}
\@ifpackageloaded{fontawesome5}{}{\usepackage{fontawesome5}}
\definecolor{quarto-callout-color}{HTML}{909090}
\definecolor{quarto-callout-note-color}{HTML}{0758E5}
\definecolor{quarto-callout-important-color}{HTML}{CC1914}
\definecolor{quarto-callout-warning-color}{HTML}{EB9113}
\definecolor{quarto-callout-tip-color}{HTML}{00A047}
\definecolor{quarto-callout-caution-color}{HTML}{FC5300}
\definecolor{quarto-callout-color-frame}{HTML}{acacac}
\definecolor{quarto-callout-note-color-frame}{HTML}{4582ec}
\definecolor{quarto-callout-important-color-frame}{HTML}{d9534f}
\definecolor{quarto-callout-warning-color-frame}{HTML}{f0ad4e}
\definecolor{quarto-callout-tip-color-frame}{HTML}{02b875}
\definecolor{quarto-callout-caution-color-frame}{HTML}{fd7e14}
\makeatother
\makeatletter
\makeatother
\makeatletter
\@ifpackageloaded{bookmark}{}{\usepackage{bookmark}}
\makeatother
\makeatletter
\@ifpackageloaded{caption}{}{\usepackage{caption}}
\AtBeginDocument{%
\ifdefined\contentsname
\renewcommand*\contentsname{Table of contents}
\else
\newcommand\contentsname{Table of contents}
\fi
\ifdefined\listfigurename
\renewcommand*\listfigurename{List of Figures}
\else
\newcommand\listfigurename{List of Figures}
\fi
\ifdefined\listtablename
\renewcommand*\listtablename{List of Tables}
\else
\newcommand\listtablename{List of Tables}
\fi
\ifdefined\figurename
\renewcommand*\figurename{Figure}
\else
\newcommand\figurename{Figure}
\fi
\ifdefined\tablename
\renewcommand*\tablename{Table}
\else
\newcommand\tablename{Table}
\fi
}
\@ifpackageloaded{float}{}{\usepackage{float}}
\floatstyle{ruled}
\@ifundefined{c@chapter}{\newfloat{codelisting}{h}{lop}}{\newfloat{codelisting}{h}{lop}[chapter]}
\floatname{codelisting}{Listing}
\newcommand*\listoflistings{\listof{codelisting}{List of Listings}}
\makeatother
\makeatletter
\@ifpackageloaded{caption}{}{\usepackage{caption}}
\@ifpackageloaded{subcaption}{}{\usepackage{subcaption}}
\makeatother
\makeatletter
\@ifpackageloaded{tcolorbox}{}{\usepackage[many]{tcolorbox}}
\makeatother
\makeatletter
\@ifundefined{shadecolor}{\definecolor{shadecolor}{rgb}{.97, .97, .97}}
\makeatother
\makeatletter
\makeatother
\ifLuaTeX
\usepackage{selnolig} % disable illegal ligatures
\fi
\IfFileExists{bookmark.sty}{\usepackage{bookmark}}{\usepackage{hyperref}}
\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
\urlstyle{same} % disable monospaced font for URLs
\hypersetup{
pdftitle={Principles and Techniques of Data Science},
pdfauthor={Kanu Grover; Bella Crouch},
colorlinks=true,
linkcolor={blue},
filecolor={Maroon},
citecolor={Blue},
urlcolor={Blue},
pdfcreator={LaTeX via pandoc}}
\title{Principles and Techniques of Data Science}
\usepackage{etoolbox}
\makeatletter
\providecommand{\subtitle}[1]{% add subtitle to \maketitle
\apptocmd{\@title}{\par {\large #1 \par}}{}{}
}
\makeatother
\subtitle{Data 100}
\author{Kanu Grover \and Bella Crouch}
\date{}
\begin{document}
\maketitle
\ifdefined\Shaded\renewenvironment{Shaded}{\begin{tcolorbox}[breakable, frame hidden, borderline west={3pt}{0pt}{shadecolor}, boxrule=0pt, enhanced, sharp corners, interior hidden]}{\end{tcolorbox}}\fi
\renewcommand*\contentsname{Table of contents}
{
\hypersetup{linkcolor=}
\setcounter{tocdepth}{2}
\tableofcontents
}
\bookmarksetup{startatroot}
\hypertarget{welcome}{%
\chapter*{Welcome}\label{welcome}}
\addcontentsline{toc}{chapter}{Welcome}
\markboth{Welcome}{Welcome}
\hypertarget{about-the-course-notes}{%
\section*{About the Course Notes}\label{about-the-course-notes}}
\addcontentsline{toc}{section}{About the Course Notes}
\markright{About the Course Notes}
This text was developed for the Spring 2023 Edition of the UC Berkeley
course Data 100: Principles and Techniques of Data Science.
As this project is in development during the Spring 2023 semester, the
course notes may be in flux. We appreciate your understanding. If you
spot any errors or would like to suggest any changes, please email us.
\textbf{Email}: data100.instructors@berkeley.edu
\bookmarksetup{startatroot}
\hypertarget{introduction}{%
\chapter{Introduction}\label{introduction}}
\begin{tcolorbox}[enhanced jigsaw, colback=white, colbacktitle=quarto-callout-note-color!10!white, titlerule=0mm, opacityback=0, breakable, bottomrule=.15mm, arc=.35mm, leftrule=.75mm, toprule=.15mm, colframe=quarto-callout-note-color-frame, bottomtitle=1mm, toptitle=1mm, opacitybacktitle=0.6, left=2mm, title=\textcolor{quarto-callout-note-color}{\faInfo}\hspace{0.5em}{Note}, coltitle=black, rightrule=.15mm]
\begin{itemize}
\tightlist
\item
Understand the stages of the data science lifecycle.
\end{itemize}
\end{tcolorbox}
Data science is an interdisciplinary field with a variety of
applications. The field is rapidly evolving; many of the key technical
underpinnings in modern-day data science have been popularized during
the early 21\textsuperscript{st} century.
A true mastery of data science requires a deep theoretical understanding
and strong grasp of domain expertise. This course will help you build on
the former -- specifically, the foundation of your technical knowledge.
To do so, we've organized concepts in Data 100 around the \textbf{data
science lifecycle}: an iterative process that encompasses the various
statistical and computational building blocks of data science.
\hypertarget{data-science-lifecycle}{%
\section{Data Science Lifecycle}\label{data-science-lifecycle}}
The data science lifecycle is a high-level overview of the data science
workflow. It's a cycle of stages that a data scientist should explore as
they conduct a thorough analysis of a data-driven problem.
There are many variations of the key ideas present in the data science
lifecycle. In Data 100, we visualize the stages of the lifecycle using a
flow diagram. Notice how there are two entry points.
\hypertarget{ask-a-question}{%
\subsection{Ask a Question}\label{ask-a-question}}
Whether by curiosity or necessity, data scientists will constantly ask
questions. For example, in the business world, data scientists may be
interested in predicting the profit generated by a certain investment.
In the field of medicine, they may ask whether some patients are more
likely than others to benefit from a treatment.
Posing questions is one of the primary ways the data science lifecycle
begins. It helps to fully define the question. Here are some things you
should ask yourself before framing a question.
\begin{itemize}
\tightlist
\item
What do we want to know?
\begin{itemize}
\tightlist
\item
A question that is too ambiguous may lead to confusion.
\end{itemize}
\item
What problems are we trying to solve?
\begin{itemize}
\tightlist
\item
The goal of asking a question should be clear in order to justify
your efforts to stakeholders.
\end{itemize}
\item
What are the hypotheses we want to test?
\begin{itemize}
\tightlist
\item
This gives a clear perspective from which to analyze final results.
\end{itemize}
\item
What are the metrics for our success?
\begin{itemize}
\tightlist
\item
This gives a clear point to know when to finish the project.
\end{itemize}
\end{itemize}
\hypertarget{obtain-data}{%
\subsection{Obtain Data}\label{obtain-data}}
The second entry point to the lifecycle is by obtaining data. A careful
analysis of any problem requires the use of data. Data may be readily
available to us, or we may have to embark on a process to collect it.
When doing so, its crucial to ask the following:
\begin{itemize}
\tightlist
\item
What data do we have and what data do we need?
\begin{itemize}
\tightlist
\item
Define the units of the data (people, cities, points in time, etc.)
and what features to measure.
\end{itemize}
\item
How will we sample more data?
\begin{itemize}
\tightlist
\item
Scrape the web, collect manually, etc.
\end{itemize}
\item
Is our data representative of the population we want to study?
\begin{itemize}
\tightlist
\item
If our data is not representative of our population of interest,
then we can come to incorrect conclusions.
\end{itemize}
\end{itemize}
Key procedures: \emph{data acquisition}, \emph{data cleaning}
\hypertarget{understand-the-data}{%
\subsection{Understand the Data}\label{understand-the-data}}
Raw data itself is not inherently useful. It's impossible to discern all
the patterns and relationships between variables without carefully
investigating them. Therefore, translating pure data to actionable
insights is a key job of a data scientist. For example, we may choose to
ask:
\begin{itemize}
\tightlist
\item
How is our data organized and what does it contain?
\begin{itemize}
\tightlist
\item
Knowing what the data says about the world helps us better
understand the world.
\end{itemize}
\item
Do we have relevant data?
\begin{itemize}
\tightlist
\item
If the data we have collected is not useful to the question at hand,
then we must collected more data.
\end{itemize}
\item
What are the biases, anomalies, or other issues with the data?
\begin{itemize}
\tightlist
\item
These can lead to many false conclusions if ignored, so data
scientists must always be aware of these issues.
\end{itemize}
\item
How do we transform the data to enable effective analysis?
\begin{itemize}
\tightlist
\item
Data is not always easy to interpret at first glance, so a data
scientist should reveal these hidden insights.
\end{itemize}
\end{itemize}
Key procedures: \emph{exploratory data analysis}, \emph{data
visualization}.
\hypertarget{understand-the-world}{%
\subsection{Understand the World}\label{understand-the-world}}
After observing the patterns in our data, we can begin answering our
question. This may require that we predict a quantity (machine
learning), or measure the effect of some treatment (inference).
From here, we may choose to report our results, or possibly conduct more
analysis. We may not be satisfied by our findings, or our initial
exploration may have brought up new questions that require a new data.
\begin{itemize}
\tightlist
\item
What does the data say about the world?
\begin{itemize}
\tightlist
\item
Given our models, the data will lead us to certain conclusions about
the real world.\\
\end{itemize}
\item
Does it answer our questions or accurately solve the problem?
\begin{itemize}
\tightlist
\item
If our model and data can not accomplish our goals, then we must
reform our question, model, or both.\\
\end{itemize}
\item
How robust are our conclusions and can we trust the predictions?
\begin{itemize}
\tightlist
\item
Inaccurate models can lead to untrue conclusions.
\end{itemize}
\end{itemize}
Key procedures: \emph{model creation}, \emph{prediction},
\emph{inference}.
\hypertarget{conclusion}{%
\section{Conclusion}\label{conclusion}}
The data science lifecycle is meant to be a set of general guidelines
rather than a hard list of requirements. In our journey exploring the
lifecycle, we'll cover both the underlying theory and technologies used
in data science, and we hope you'll build an appreciation for the field.
With that, let's begin by introducing one of the most important tools in
exploratory data analysis: \texttt{pandas}.
\bookmarksetup{startatroot}
\hypertarget{pandas-i}{%
\chapter{Pandas I}\label{pandas-i}}
\begin{tcolorbox}[enhanced jigsaw, colback=white, colbacktitle=quarto-callout-note-color!10!white, titlerule=0mm, opacityback=0, breakable, bottomrule=.15mm, arc=.35mm, leftrule=.75mm, toprule=.15mm, colframe=quarto-callout-note-color-frame, bottomtitle=1mm, toptitle=1mm, opacitybacktitle=0.6, left=2mm, title=\textcolor{quarto-callout-note-color}{\faInfo}\hspace{0.5em}{Note}, coltitle=black, rightrule=.15mm]
\begin{itemize}
\tightlist
\item
Build familiarity with basic \texttt{pandas} syntax
\item
Learn the methods of selecting and filtering data from a DataFrame.
\item
Understand the differences between DataFrames and Series
\end{itemize}
\end{tcolorbox}
Data scientists work with data stored in a variety of formats. The
primary focus of this class is in understanding tabular data -- one of
the most widely used formats in data science. This note introduces
DataFrames, which are among the most popular representations of tabular
data. We'll also introduce \texttt{pandas}, the standard Python package
for manipulating data in DataFrames.
\hypertarget{introduction-to-exploratory-data-analysis}{%
\section{Introduction to Exploratory Data
Analysis}\label{introduction-to-exploratory-data-analysis}}
Imagine you collected, or have been given a box of data. What do you do
next?
The first step is to clean your data. \textbf{Data cleaning} often
corrects issues in the structure and formatting of data, including
missing values and unit conversions.
Data scientists have coined the term \textbf{exploratory data analysis
(EDA)} to describe the process of transforming raw data to insightful
observations. EDA is an \emph{open-ended} analysis of transforming,
visualizing, and summarizing patterns in data. In order to conduct EDA,
we first need to familiarize ourselves with \texttt{pandas} -- an
important programming tool.
\hypertarget{introduction-to-pandas}{%
\section{Introduction to Pandas}\label{introduction-to-pandas}}
\texttt{pandas} is a data analysis library to make data cleaning and
analysis fast and convenient in Python.
The \texttt{pandas} library adopts many coding idioms from
\texttt{NumPy}. The biggest difference is that \texttt{pandas} is
designed for working with tabular data, one of the most common data
formats (and the focus of Data 100).
Before writing any code, we must import \texttt{pandas} into our Python
environment.
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# \textasciigrave{}pd\textasciigrave{} is the conventional alias for Pandas, as \textasciigrave{}np\textasciigrave{} is for NumPy}
\ImportTok{import}\NormalTok{ pandas }\ImportTok{as}\NormalTok{ pd}
\end{Highlighting}
\end{Shaded}
\hypertarget{series-dataframes-and-indices}{%
\section{Series, DataFrames, and
Indices}\label{series-dataframes-and-indices}}
There are three fundamental data structures in \texttt{pandas}:
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\tightlist
\item
\textbf{Series}: 1D labeled array data; best thought of as columnar
data
\item
\textbf{DataFrame}: 2D tabular data with rows and columns
\item
\textbf{Index}: A sequence of row/column labels
\end{enumerate}
DataFrames, Series, and Indices can be represented visually in the
following diagram.
\includegraphics{pandas_1/images/df_series_index.png}
Notice how the \textbf{DataFrame} is a two dimensional object -- it
contains both rows and columns. The \textbf{Series} above is a singular
column of this DataFrame, namely the \texttt{Candidate} column. Both
contain an \textbf{Index}, or a shared list of row labels (the integers
from 0 to 5, inclusive).
\hypertarget{series}{%
\subsection{Series}\label{series}}
A Series represents a column of a DataFrame; more generally, it can be
any 1-dimensional array-like object containing values of the same type
with associated data labels, called its index.
\begin{Shaded}
\begin{Highlighting}[]
\ImportTok{import}\NormalTok{ pandas }\ImportTok{as}\NormalTok{ pd}
\NormalTok{s }\OperatorTok{=}\NormalTok{ pd.Series([}\OperatorTok{{-}}\DecValTok{1}\NormalTok{, }\DecValTok{10}\NormalTok{, }\DecValTok{2}\NormalTok{])}
\BuiltInTok{print}\NormalTok{(s)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
0 -1
1 10
2 2
dtype: int64
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{s.array }\CommentTok{\# Data contained within the Series}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
<PandasArray>
[-1, 10, 2]
Length: 3, dtype: int64
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{s.index }\CommentTok{\# The Index of the Series}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
RangeIndex(start=0, stop=3, step=1)
\end{verbatim}
By default, row indices in \texttt{pandas} are a sequential list of
integers beginning from 0. Optionally, a list of desired indices can be
passed to the \texttt{index} argument.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{s }\OperatorTok{=}\NormalTok{ pd.Series([}\OperatorTok{{-}}\DecValTok{1}\NormalTok{, }\DecValTok{10}\NormalTok{, }\DecValTok{2}\NormalTok{], index }\OperatorTok{=}\NormalTok{ [}\StringTok{"a"}\NormalTok{, }\StringTok{"b"}\NormalTok{, }\StringTok{"c"}\NormalTok{])}
\BuiltInTok{print}\NormalTok{(s)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
a -1
b 10
c 2
dtype: int64
\end{verbatim}
Indices can also be changed after initialization.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{s.index }\OperatorTok{=}\NormalTok{ [}\StringTok{"first"}\NormalTok{, }\StringTok{"second"}\NormalTok{, }\StringTok{"third"}\NormalTok{]}
\BuiltInTok{print}\NormalTok{(s)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
first -1
second 10
third 2
dtype: int64
\end{verbatim}
\hypertarget{selection-in-series}{%
\subsubsection{Selection in Series}\label{selection-in-series}}
Similar to an array, we can select a single value or a set of values
from a Series. There are 3 primary methods of selecting data.
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\tightlist
\item
A single index label
\item
A list of index labels
\item
A filtering condition
\end{enumerate}
Let's define the following Series \texttt{ser}.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{ser }\OperatorTok{=}\NormalTok{ pd.Series([}\DecValTok{4}\NormalTok{, }\OperatorTok{{-}}\DecValTok{2}\NormalTok{, }\DecValTok{0}\NormalTok{, }\DecValTok{6}\NormalTok{], index }\OperatorTok{=}\NormalTok{ [}\StringTok{"a"}\NormalTok{, }\StringTok{"b"}\NormalTok{, }\StringTok{"c"}\NormalTok{, }\StringTok{"d"}\NormalTok{])}
\BuiltInTok{print}\NormalTok{(ser)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
a 4
b -2
c 0
d 6
dtype: int64
\end{verbatim}
\hypertarget{a-single-index-label}{%
\paragraph{A Single Index Label}\label{a-single-index-label}}
\begin{Shaded}
\begin{Highlighting}[]
\BuiltInTok{print}\NormalTok{(ser[}\StringTok{"a"}\NormalTok{]) }\CommentTok{\# Notice how the return value is a single array element}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
4
\end{verbatim}
\hypertarget{a-list-of-index-labels}{%
\paragraph{A List of Index Labels}\label{a-list-of-index-labels}}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{ser[[}\StringTok{"a"}\NormalTok{, }\StringTok{"c"}\NormalTok{]] }\CommentTok{\# Notice how the return value is another Series}
\end{Highlighting}
\end{Shaded}
\begin{tabular}{lr}
\toprule
{} & 0 \\
\midrule
a & 4 \\
c & 0 \\
\bottomrule
\end{tabular}
\hypertarget{a-filtering-condition}{%
\paragraph{A Filtering Condition}\label{a-filtering-condition}}
Perhaps the most interesting (and useful) method of selecting data from
a Series is with a filtering condition.
We first must apply a vectorized boolean operation to our Series that
encodes the filter conditon.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{ser }\OperatorTok{\textgreater{}} \DecValTok{0} \CommentTok{\# Filter condition: select all elements greater than 0}
\end{Highlighting}
\end{Shaded}
\begin{tabular}{ll}
\toprule
{} & 0 \\
\midrule
a & True \\
b & False \\
c & False \\
d & True \\
\bottomrule
\end{tabular}
Upon ``indexing'' in our Series with this condition, \texttt{pandas}
selects only the rows with \texttt{True} values.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{ser[ser }\OperatorTok{\textgreater{}} \DecValTok{0}\NormalTok{] }
\end{Highlighting}
\end{Shaded}
\begin{tabular}{lr}
\toprule
{} & 0 \\
\midrule
a & 4 \\
d & 6 \\
\bottomrule
\end{tabular}
\hypertarget{dataframes}{%
\subsection{DataFrames}\label{dataframes}}
In Data 8, you encountered the \texttt{Table} class of the
\texttt{datascience} library, which represented tabular data. In Data
100, we'll be using the \texttt{DataFrame} class of the \texttt{pandas}
library.
Here is an example of a DataFrame that contains election data.
\begin{Shaded}
\begin{Highlighting}[]
\ImportTok{import}\NormalTok{ pandas }\ImportTok{as}\NormalTok{ pd}
\NormalTok{elections }\OperatorTok{=}\NormalTok{ pd.read\_csv(}\StringTok{"data/elections.csv"}\NormalTok{)}
\NormalTok{elections}
\end{Highlighting}
\end{Shaded}
\begin{tabular}{lrllrlr}
\toprule
{} & Year & Candidate & Party & Popular vote & Result & \% \\
\midrule
0 & 1824 & Andrew Jackson & Democratic-Republican & 151271 & loss & 57.210122 \\
1 & 1824 & John Quincy Adams & Democratic-Republican & 113142 & win & 42.789878 \\
2 & 1828 & Andrew Jackson & Democratic & 642806 & win & 56.203927 \\
3 & 1828 & John Quincy Adams & National Republican & 500897 & loss & 43.796073 \\
4 & 1832 & Andrew Jackson & Democratic & 702735 & win & 54.574789 \\
5 & 1832 & Henry Clay & National Republican & 484205 & loss & 37.603628 \\
6 & 1832 & William Wirt & Anti-Masonic & 100715 & loss & 7.821583 \\
7 & 1836 & Hugh Lawson White & Whig & 146109 & loss & 10.005985 \\
8 & 1836 & Martin Van Buren & Democratic & 763291 & win & 52.272472 \\
9 & 1836 & William Henry Harrison & Whig & 550816 & loss & 37.721543 \\
10 & 1840 & Martin Van Buren & Democratic & 1128854 & loss & 46.948787 \\
11 & 1840 & William Henry Harrison & Whig & 1275583 & win & 53.051213 \\
12 & 1844 & Henry Clay & Whig & 1300004 & loss & 49.250523 \\
13 & 1844 & James Polk & Democratic & 1339570 & win & 50.749477 \\
14 & 1848 & Lewis Cass & Democratic & 1223460 & loss & 42.552229 \\
15 & 1848 & Martin Van Buren & Free Soil & 291501 & loss & 10.138474 \\
16 & 1848 & Zachary Taylor & Whig & 1360235 & win & 47.309296 \\
17 & 1852 & Franklin Pierce & Democratic & 1605943 & win & 51.013168 \\
18 & 1852 & John P. Hale & Free Soil & 155210 & loss & 4.930283 \\
19 & 1852 & Winfield Scott & Whig & 1386942 & loss & 44.056548 \\
20 & 1856 & James Buchanan & Democratic & 1835140 & win & 45.306080 \\
21 & 1856 & John C. Frémont & Republican & 1342345 & loss & 33.139919 \\
22 & 1856 & Millard Fillmore & American & 873053 & loss & 21.554001 \\
23 & 1860 & Abraham Lincoln & Republican & 1855993 & win & 39.699408 \\
24 & 1860 & John Bell & Constitutional Union & 590901 & loss & 12.639283 \\
25 & 1860 & John C. Breckinridge & Southern Democratic & 848019 & loss & 18.138998 \\
26 & 1860 & Stephen A. Douglas & Northern Democratic & 1380202 & loss & 29.522311 \\
27 & 1864 & Abraham Lincoln & National Union & 2211317 & win & 54.951512 \\
28 & 1864 & George B. McClellan & Democratic & 1812807 & loss & 45.048488 \\
29 & 1868 & Horatio Seymour & Democratic & 2708744 & loss & 47.334695 \\
30 & 1868 & Ulysses Grant & Republican & 3013790 & win & 52.665305 \\
31 & 1872 & Horace Greeley & Liberal Republican & 2834761 & loss & 44.071406 \\
32 & 1872 & Ulysses Grant & Republican & 3597439 & win & 55.928594 \\
33 & 1876 & Rutherford Hayes & Republican & 4034142 & win & 48.471624 \\
34 & 1876 & Samuel J. Tilden & Democratic & 4288546 & loss & 51.528376 \\
35 & 1880 & James B. Weaver & Greenback & 308649 & loss & 3.352344 \\
36 & 1880 & James Garfield & Republican & 4453337 & win & 48.369234 \\
37 & 1880 & Winfield Scott Hancock & Democratic & 4444976 & loss & 48.278422 \\
38 & 1884 & Benjamin Butler & Anti-Monopoly & 134294 & loss & 1.335838 \\
39 & 1884 & Grover Cleveland & Democratic & 4914482 & win & 48.884933 \\
40 & 1884 & James G. Blaine & Republican & 4856905 & loss & 48.312208 \\
41 & 1884 & John St. John & Prohibition & 147482 & loss & 1.467021 \\
42 & 1888 & Alson Streeter & Union Labor & 146602 & loss & 1.288861 \\
43 & 1888 & Benjamin Harrison & Republican & 5443633 & win & 47.858041 \\
44 & 1888 & Clinton B. Fisk & Prohibition & 249819 & loss & 2.196299 \\
45 & 1888 & Grover Cleveland & Democratic & 5534488 & loss & 48.656799 \\
46 & 1892 & Benjamin Harrison & Republican & 5176108 & loss & 42.984101 \\
47 & 1892 & Grover Cleveland & Democratic & 5553898 & win & 46.121393 \\
48 & 1892 & James B. Weaver & Populist & 1041028 & loss & 8.645038 \\
49 & 1892 & John Bidwell & Prohibition & 270879 & loss & 2.249468 \\
50 & 1896 & John M. Palmer & National Democratic & 134645 & loss & 0.969566 \\
51 & 1896 & Joshua Levering & Prohibition & 131312 & loss & 0.945565 \\
52 & 1896 & William Jennings Bryan & Democratic & 6509052 & loss & 46.871053 \\
53 & 1896 & William McKinley & Republican & 7112138 & win & 51.213817 \\
54 & 1900 & John G. Woolley & Prohibition & 210864 & loss & 1.526821 \\
55 & 1900 & William Jennings Bryan & Democratic & 6370932 & loss & 46.130540 \\
56 & 1900 & William McKinley & Republican & 7228864 & win & 52.342640 \\
57 & 1904 & Alton B. Parker & Democratic & 5083880 & loss & 37.685116 \\
58 & 1904 & Eugene V. Debs & Socialist & 402810 & loss & 2.985897 \\
59 & 1904 & Silas C. Swallow & Prohibition & 259102 & loss & 1.920637 \\
60 & 1904 & Theodore Roosevelt & Republican & 7630557 & win & 56.562787 \\
61 & 1904 & Thomas E. Watson & Populist & 114070 & loss & 0.845563 \\
62 & 1908 & Eugene V. Debs & Socialist & 420852 & loss & 2.850866 \\
63 & 1908 & Eugene W. Chafin & Prohibition & 254087 & loss & 1.721194 \\
64 & 1908 & William Jennings Bryan & Democratic & 6408979 & loss & 43.414640 \\
65 & 1908 & William Taft & Republican & 7678335 & win & 52.013300 \\
66 & 1912 & Eugene V. Debs & Socialist & 901551 & loss & 6.004354 \\
67 & 1912 & Eugene W. Chafin & Prohibition & 208156 & loss & 1.386325 \\
68 & 1912 & Theodore Roosevelt & Progressive & 4122721 & loss & 27.457433 \\
69 & 1912 & William Taft & Republican & 3486242 & loss & 23.218466 \\
70 & 1912 & Woodrow Wilson & Democratic & 6296284 & win & 41.933422 \\
71 & 1916 & Allan L. Benson & Socialist & 590524 & loss & 3.194193 \\
72 & 1916 & Charles Evans Hughes & Republican & 8548728 & loss & 46.240779 \\
73 & 1916 & Frank Hanly & Prohibition & 221302 & loss & 1.197041 \\
74 & 1916 & Woodrow Wilson & Democratic & 9126868 & win & 49.367987 \\
75 & 1920 & Aaron S. Watkins & Prohibition & 188787 & loss & 0.708351 \\
76 & 1920 & Eugene V. Debs & Socialist & 913693 & loss & 3.428282 \\
77 & 1920 & James M. Cox & Democratic & 9139661 & loss & 34.293063 \\
78 & 1920 & Parley P. Christensen & Farmer–Labor & 265398 & loss & 0.995804 \\
79 & 1920 & Warren Harding & Republican & 16144093 & win & 60.574501 \\
80 & 1924 & Calvin Coolidge & Republican & 15723789 & win & 54.329113 \\
81 & 1924 & John W. Davis & Democratic & 8386242 & loss & 28.976291 \\
82 & 1924 & Robert La Follette & Progressive & 4831706 & loss & 16.694596 \\
83 & 1928 & Al Smith & Democratic & 15015464 & loss & 40.902853 \\
84 & 1928 & Herbert Hoover & Republican & 21427123 & win & 58.368524 \\
85 & 1928 & Norman Thomas & Socialist & 267478 & loss & 0.728623 \\
86 & 1932 & Franklin Roosevelt & Democratic & 22821277 & win & 57.672125 \\
87 & 1932 & Herbert Hoover & Republican & 15761254 & loss & 39.830594 \\
88 & 1932 & Norman Thomas & Socialist & 884885 & loss & 2.236211 \\
89 & 1932 & William Z. Foster & Communist & 103307 & loss & 0.261069 \\
90 & 1936 & Alf Landon & Republican & 16679543 & loss & 36.648285 \\
91 & 1936 & Franklin Roosevelt & Democratic & 27752648 & win & 60.978107 \\
92 & 1936 & Norman Thomas & Socialist & 187910 & loss & 0.412876 \\
93 & 1936 & William Lemke & Union & 892378 & loss & 1.960733 \\
94 & 1940 & Franklin Roosevelt & Democratic & 27313945 & win & 54.871202 \\
95 & 1940 & Norman Thomas & Socialist & 116599 & loss & 0.234237 \\
96 & 1940 & Wendell Willkie & Republican & 22347744 & loss & 44.894561 \\
97 & 1944 & Franklin Roosevelt & Democratic & 25612916 & win & 53.773801 \\
98 & 1944 & Thomas E. Dewey & Republican & 22017929 & loss & 46.226199 \\
99 & 1948 & Claude A. Watson & Prohibition & 103708 & loss & 0.212747 \\
100 & 1948 & Harry Truman & Democratic & 24179347 & win & 49.601536 \\
101 & 1948 & Henry A. Wallace & Progressive & 1157328 & loss & 2.374144 \\
102 & 1948 & Norman Thomas & Socialist & 139569 & loss & 0.286312 \\
103 & 1948 & Strom Thurmond & Dixiecrat & 1175930 & loss & 2.412304 \\
104 & 1948 & Thomas E. Dewey & Republican & 21991292 & loss & 45.112958 \\
105 & 1952 & Adlai Stevenson & Democratic & 27375090 & loss & 44.446312 \\
106 & 1952 & Dwight Eisenhower & Republican & 34075529 & win & 55.325173 \\
107 & 1952 & Vincent Hallinan & Progressive & 140746 & loss & 0.228516 \\
108 & 1956 & Adlai Stevenson & Democratic & 26028028 & loss & 42.174464 \\
109 & 1956 & Dwight Eisenhower & Republican & 35579180 & win & 57.650654 \\
110 & 1956 & T. Coleman Andrews & States' Rights & 107929 & loss & 0.174883 \\
111 & 1960 & John Kennedy & Democratic & 34220984 & win & 50.082561 \\
112 & 1960 & Richard Nixon & Republican & 34108157 & loss & 49.917439 \\
113 & 1964 & Barry Goldwater & Republican & 27175754 & loss & 38.655297 \\
114 & 1964 & Lyndon Johnson & Democratic & 43127041 & win & 61.344703 \\
115 & 1968 & George Wallace & American Independent & 9901118 & loss & 13.571218 \\
116 & 1968 & Hubert Humphrey & Democratic & 31271839 & loss & 42.863537 \\
117 & 1968 & Richard Nixon & Republican & 31783783 & win & 43.565246 \\
118 & 1972 & George McGovern & Democratic & 29173222 & loss & 37.670670 \\
119 & 1972 & John G. Schmitz & American Independent & 1100868 & loss & 1.421524 \\
120 & 1972 & Richard Nixon & Republican & 47168710 & win & 60.907806 \\
121 & 1976 & Eugene McCarthy & Independent & 740460 & loss & 0.911649 \\
122 & 1976 & Gerald Ford & Republican & 39148634 & loss & 48.199499 \\
123 & 1976 & Jimmy Carter & Democratic & 40831881 & win & 50.271900 \\
124 & 1976 & Lester Maddox & American Independent & 170274 & loss & 0.209640 \\
125 & 1976 & Roger MacBride & Libertarian & 172557 & loss & 0.212451 \\
126 & 1976 & Thomas J. Anderson & American & 158271 & loss & 0.194862 \\
127 & 1980 & Barry Commoner & Citizens & 233052 & loss & 0.270182 \\
128 & 1980 & Ed Clark & Libertarian & 921128 & loss & 1.067883 \\
129 & 1980 & Jimmy Carter & Democratic & 35480115 & loss & 41.132848 \\
130 & 1980 & John B. Anderson & Independent & 5719850 & loss & 6.631143 \\
131 & 1980 & Ronald Reagan & Republican & 43903230 & win & 50.897944 \\
132 & 1984 & David Bergland & Libertarian & 228111 & loss & 0.247245 \\
133 & 1984 & Ronald Reagan & Republican & 54455472 & win & 59.023326 \\
134 & 1984 & Walter Mondale & Democratic & 37577352 & loss & 40.729429 \\
135 & 1988 & George H. W. Bush & Republican & 48886597 & win & 53.518845 \\
136 & 1988 & Lenora Fulani & New Alliance & 217221 & loss & 0.237804 \\
137 & 1988 & Michael Dukakis & Democratic & 41809074 & loss & 45.770691 \\
138 & 1988 & Ron Paul & Libertarian & 431750 & loss & 0.472660 \\
139 & 1992 & Andre Marrou & Libertarian & 290087 & loss & 0.278516 \\
140 & 1992 & Bill Clinton & Democratic & 44909806 & win & 43.118485 \\
141 & 1992 & Bo Gritz & Populist & 106152 & loss & 0.101918 \\
142 & 1992 & George H. W. Bush & Republican & 39104550 & loss & 37.544784 \\
143 & 1992 & Ross Perot & Independent & 19743821 & loss & 18.956298 \\
144 & 1996 & Bill Clinton & Democratic & 47400125 & win & 49.296938 \\
145 & 1996 & Bob Dole & Republican & 39197469 & loss & 40.766036 \\
146 & 1996 & Harry Browne & Libertarian & 485759 & loss & 0.505198 \\
147 & 1996 & Howard Phillips & Taxpayers & 184656 & loss & 0.192045 \\
148 & 1996 & John Hagelin & Natural Law & 113670 & loss & 0.118219 \\
149 & 1996 & Ralph Nader & Green & 685297 & loss & 0.712721 \\
150 & 1996 & Ross Perot & Reform & 8085294 & loss & 8.408844 \\
151 & 2000 & Al Gore & Democratic & 50999897 & loss & 48.491813 \\
152 & 2000 & George W. Bush & Republican & 50456002 & win & 47.974666 \\
153 & 2000 & Harry Browne & Libertarian & 384431 & loss & 0.365525 \\
154 & 2000 & Pat Buchanan & Reform & 448895 & loss & 0.426819 \\
155 & 2000 & Ralph Nader & Green & 2882955 & loss & 2.741176 \\
156 & 2004 & David Cobb & Green & 119859 & loss & 0.098088 \\
157 & 2004 & George W. Bush & Republican & 62040610 & win & 50.771824 \\
158 & 2004 & John Kerry & Democratic & 59028444 & loss & 48.306775 \\
159 & 2004 & Michael Badnarik & Libertarian & 397265 & loss & 0.325108 \\
160 & 2004 & Michael Peroutka & Constitution & 143630 & loss & 0.117542 \\
161 & 2004 & Ralph Nader & Independent & 465151 & loss & 0.380663 \\
162 & 2008 & Barack Obama & Democratic & 69498516 & win & 53.023510 \\
163 & 2008 & Bob Barr & Libertarian & 523715 & loss & 0.399565 \\
164 & 2008 & Chuck Baldwin & Constitution & 199750 & loss & 0.152398 \\
165 & 2008 & Cynthia McKinney & Green & 161797 & loss & 0.123442 \\
166 & 2008 & John McCain & Republican & 59948323 & loss & 45.737243 \\
167 & 2008 & Ralph Nader & Independent & 739034 & loss & 0.563842 \\
168 & 2012 & Barack Obama & Democratic & 65915795 & win & 51.258484 \\
169 & 2012 & Gary Johnson & Libertarian & 1275971 & loss & 0.992241 \\
170 & 2012 & Jill Stein & Green & 469627 & loss & 0.365199 \\
171 & 2012 & Mitt Romney & Republican & 60933504 & loss & 47.384076 \\
172 & 2016 & Darrell Castle & Constitution & 203091 & loss & 0.149640 \\
173 & 2016 & Donald Trump & Republican & 62984828 & win & 46.407862 \\
174 & 2016 & Evan McMullin & Independent & 732273 & loss & 0.539546 \\
175 & 2016 & Gary Johnson & Libertarian & 4489235 & loss & 3.307714 \\
176 & 2016 & Hillary Clinton & Democratic & 65853514 & loss & 48.521539 \\
177 & 2016 & Jill Stein & Green & 1457226 & loss & 1.073699 \\
178 & 2020 & Joseph Biden & Democratic & 81268924 & win & 51.311515 \\
179 & 2020 & Donald Trump & Republican & 74216154 & loss & 46.858542 \\
180 & 2020 & Jo Jorgensen & Libertarian & 1865724 & loss & 1.177979 \\
181 & 2020 & Howard Hawkins & Green & 405035 & loss & 0.255731 \\
\bottomrule
\end{tabular}
Let's dissect the code above.
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
We first import the \texttt{pandas} library into our Python
environment, using the alias \texttt{pd}.
\texttt{import\ pandas\ as\ pd}
\item
There are a number of ways to read data into a DataFrame. In Data 100,
our data are typically stored in a CSV (comma-seperated values) file
format. We can import a CSV file into a DataFrame by passing the data
path as an argument to the following \texttt{pandas} function.
\texttt{pd.read\_csv("elections.csv")}
\end{enumerate}
This code stores our DataFrame object in the \texttt{elections}
variable. Upon inspection, our \texttt{elections} DataFrame has 182 rows
and 6 columns (\texttt{Year}, \texttt{Candidate}, \texttt{Party},
\texttt{Popular\ Vote}, \texttt{Result}, \texttt{\%}). Each row
represents a single record -- in our example, a presedential candidate
from some particular year. Each column represents a single attribute, or
feature of the record.
In the example above, we constructed a DataFrame object using data from
a CSV file. As we'll explore in the next section, we can create a
DataFrame with data of our own.
\hypertarget{creating-a-dataframe}{%
\subsubsection{Creating a DataFrame}\label{creating-a-dataframe}}