-
Notifications
You must be signed in to change notification settings - Fork 6
/
exercises.qmd
1301 lines (685 loc) · 31 KB
/
exercises.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: 'Walkthroughs and Exercises for *Data Analysis in Python*'
author: "Dr. Chester Ismay"
format: html
engine: knitr
---
```{python}
#| include: false
import pandas as pd
# Display all columns
pd.set_option('display.max_columns', None)
# Display all outputs from each cell
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
```
# Intro: Foundations of Data Analysis with Python
## Walkthrough #1: Setting Up the Python Environment
If you haven't already installed Python, Jupyter, and the necessary packages, there are instructions on the course repo in the README to do so [here](https://github.com/ismayc/oreilly-data-analysis-with-python/blob/main/README.md).
If you aren't able to do this on your machine, you may want to check out [Google Colab](https://colab.research.google.com/). It's a free service that allows you to run Jupyter notebooks in the cloud.
```{python}
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# For plotly to load directly in Jupyter notebook
import plotly.offline as pyo
pyo.init_notebook_mode(connected=True)
```
## Exercise #1: Setting Up the Python Environment
By completing this exercise, you will be able to
- Import necessary Python packages
- Check for successful package loading
Follow the instructions above in Walkthrough #1 to check for correct installation
of necessary packages. We'll wait a few minutes to make sure as many of you are
set up as possible. Please give a thumbs up in the pulse check if you are ready
to move on.
---
# Module 1: Data Wrangling with Pandas
## Walkthrough #2: Loading and Inspecting Data with Pandas
### Import data from a CSV or from an Excel file
```{python}
# Load the data from a CSV file
# Or load the data from an Excel file
```
### Perform an initial exploration of the data
```{python}
# Display the first few rows of the DataFrame
```
```{python}
# Display the information about the DataFrame
```
```{python}
# Display summary statistics of the DataFrame
```
```{python}
# Check for missing data
```
```{python}
# Check data types
```
## Exercise #2: Loading and Inspecting Data with Pandas
By completing this exercise, you will be able to use `pandas` to
- Import data from a CSV or from an Excel file
- Perform an initial exploration of the data
```{python}
# Load the populations data from an Excel file
# Inspection methods for populations DataFrame
# Checking for missing data and data types for populations DataFrame
```
## Walkthrough #3: Cleaning and Preparing Data with Pandas
### Handle missing data
#### Remove rows
```{python}
# Remove rows with any missing values
```
```{python}
# Remove rows only if all values are missing
```
```{python}
# Remove rows with missing values in specific columns
```
#### Remove columns
```{python}
# Remove columns with any missing values
# Display the DataFrame after removing columns with missing values
```
#### Replace missing values with specific value
```{python}
# Replace missing values with a specific value (e.g., 0 for numerical columns, 'Unknown' for categorical columns)
# Display the DataFrame after replacing missing values with specific values
```
This can be extended to replace missing values with the mean, median, or mode of the column too, but that's beyond the scope of this course.
### Convert a column to a different data type
```{python}
# Change year to be a string instead of an integer
# Display the information on the DataFrame with year as a string
```
```{python}
# Change the year of string type back to integer
# Display the information on the DataFrame with year as a string
```
### Rename a column
```{python}
# Rename the 'income_group' column to 'income_category'
```
### Changing a DataFrame’s index
#### Set the index
```{python}
# Set unique combinations of 'code' and 'year' as the index
```
#### Reset the index
```{python}
# Reset the index
```
### Filtering rows based on conditions
#### Conditions on a single column
```{python}
# Filter rows where 'gdp_percapita' is greater than 20,000
```
```{python}
# Filter rows where 'income_group' is 'High income'
```
```{python}
# Filter rows where total_investment is not NaN
```
#### Conditions on multiple columns
```{python}
# Filter rows where inflation_rate is less than 0 and income_group is 'Low income'
```
```{python}
# Filter rows where gdp_percapita is greater than 40,000 and year is less than or equal to 2016
```
## Exercise #3: Cleaning and Preparing Data with Pandas
By completing this exercise, you will be able to use `pandas` to
- Handle missing data
- Convert a column to a different data type
- Rename a column
- Change a DataFrame’s index
- Filter a DataFrame
### Handle Missing Data
#### Remove rows
```{python}
# Remove rows with any missing values
```
```{python}
# Remove rows only if all values are missing
```
```{python}
# Remove rows with missing values in specific columns (e.g., 'fertility_rate', 'life_expectancy')
```
#### Remove columns
```{python}
# Remove columns with any missing values
```
#### Replace missing values with specific value
```{python}
# Replace missing values with a specific value (e.g., 0 for numerical columns,
# 'Unknown' for categorical columns)
```
### Convert a Column to a Different Data Type and Rename a Column
#### Convert a Column to a Different Data Type
```{python}
# Convert the 'year' column to string type
```
```{python}
# Convert it back to integer
```
#### Rename a Column
```{python}
# Rename the 'fertility_rate' column to 'fertility'
```
### Change a DataFrame’s Index and Filter a DataFrame
#### Change a DataFrame’s Index
```{python}
# Set the 'country_code' column as the index
```
#### Filter a DataFrame
```{python}
# Filter the DataFrame to include only rows where the 'continent' is 'Asia'
```
```{python}
# Filter the DataFrame to include only rows where the 'year' is 2020
```
```{python}
# Filter the DataFrame to include only rows where the 'fertility_rate' is greater than 2
```
## Walkthrough #4: Transforming and Aggregating Data with Pandas
### Grouping data
```{python}
```
### Applying Functions
#### Applying a function element-wise with `map()`
```{python}
# Convert income_group to uppercase using map()
```
#### Applying a Function to Groups with `groupby()` and `agg()`
```{python}
# Calculate the median gdp_percapita and inflation_rate for each income_group
```
### Summary tables
```{python}
# Create a pivot table of gdp_percapita and inflation_rate by income_group and year
```
### Analyzing categorical data
#### Using cross-tabulation
```{python}
# Show counts of income_group by year
```
#### By getting group counts
```{python}
# Count the occurrences of each income_group
```
## Exercise #4: Transforming and Aggregating Data with Pandas
By completing this exercise, you will be able to use `pandas` to
- Aggregate data effectively by grouping it
- Transform data by applying functions element-wise or to groups
- Create summary tables
- Analyze categorical data using cross-tabulation and counts
### Grouping Data
```{python}
# Group data by continent and calculate the mean life expectancy
```
### Applying Functions
#### Applying a function element-wise with `map()`
```{python}
# Convert continent to uppercase using map()
```
#### Applying a function to groups with `groupby()` and `agg()`
```{python}
# Calculate the median fertility rate and life expectancy for each continent
```
### Summary Tables
```{python}
# Create a pivot table of fertility rate and life expectancy by continent and year
```
### Analyzing Categorical Data
#### Using Cross-Tabulation
```{python}
# Create a cross-tabulation of continent and year
```
#### By Getting Group Counts
```{python}
# Count the occurrences of each region
```
---
# Module 2: Data Visualization Basics with Matplotlib and Seaborn
## Walkthrough #5: Creating Basic Plots with Matplotlib
### Line plot
```{python}
# Filter data for a specific country
```
### Bar chart
```{python}
# Filter data for Caribbean countries and the year 2020
# Bar chart of gdp_percapita for different Caribbean countries in 2020
```
### Adding labels and titles
```{python}
# Filter data for a specific country
# Line plot of gdp_percapita over the years with labels and titles
```
### Adjusting axes and tick marks
```{python}
# Bar chart of gdp_percapita for different Caribbean countries in 2020 with
# adjusted axes and tick marks
# Adjust axes
# Adjust tick marks
```
## Exercise #5: Creating Basic Plots with Matplotlib
By completing this exercise, you will be able to use `matplotlib` to
- Create line plots and bar charts
- Add labels and titles
- Adjust axes and tick marks
### Line Plot
```{python}
# Filter data for India
# Line plot of fertility rate over the years
```
### Bar Chart
```{python}
# Filter data for selected Asian countries and the year 2020
# Bar chart of population size for selected Asian countries in 2020
```
### Adding Labels and Titles
```{python}
# Filter data for Nigeria
# Line plot of life expectancy over the years with labels and titles
```
### Adjusting Axes and Tick Marks
```{python}
# Filter data for selected African countries ('NGA', 'ETH', 'EGY', 'ZAF', 'DZA')
# and the year 2020
# Need to convert year back to an integer?
# Bar chart of fertility rate for selected African countries in 2020 with
# adjusted axes and tick marks
# Adjust axes
# Adjust tick marks
```
## Walkthrough #6: Data Visualization Techniques with Seaborn
### Heatmap
```{python}
# Select only the numeric columns
# Calculate correlation matrix
# Create heatmap
```
### Pair plot
```{python}
```
### Violin plot
```{python}
```
### Customizing Seaborn plots
```{python}
# Bar plot with customization
# Customizing axes and tick marks
```
## Exercise #6: Data Visualization Techniques with Seaborn
By completing this exercise, you will be able to use `seaborn` to
- Create heatmaps
- Design pair plots and violin plots
- Customize Seaborn plots
### Heatmap
```{python}
# Select only the numeric columns
# Calculate correlation matrix
# Create heatmap
```
### Pair Plot
```{python}
# Pair plot of fertility rate, life expectancy, and population size
```
### Violin Plot
```{python}
# Violin plot of fertility rate by continent
```
### Customizing Seaborn Plots
```{python}
# Filter data for selected European countries ('DEU', 'FRA', 'ITA', 'ESP', 'GBR')
# and the year 2020
# Bar plot with customization
# Customizing axes and tick marks
```
---
# Module 3: Interactive Data Visualization with Plotly
## Walkthrough #7: Interactive Charts and Dashboards with Plotly
### Basic interactive chart
```{python}
# Filter data for a specific country
# Create an interactive line chart
```
### Adding interactive elements
```{python}
# Create an interactive scatter plot
# Add hover, zoom, and selection tools
```
### Designing a simple dashboard
```{python}
# Filter data for the year 2020
# Create a subplot figure with 1 row and 2 columns
# Line chart of GDP Per Capita for Afghanistan
# Bar chart of GDP Per Capita for different countries in 2020
# Update layout
```
## Exercise #7: Interactive Charts and Dashboards with Plotly
By completing this exercise, you will be able to use `plotly` to
- Create a basic interactive chart
- Add interactive elements: hover, zoom, and selection tools
- Design a simple dashboard with multiple charts
### Basic Interactive Chart
```{python}
# Filter data for a specific country (Brazil)
# Create an interactive line chart (Fertility Rate Over Years)
```
### Adding Interactive Elements
```{python}
# Create an interactive scatter plot
# Add hover, zoom, and selection tools
```
### Designing a Simple Dashboard
```{python}
# Filter data for the year 2020
# Create a subplot figure with 1 row and 2 columns
# Line chart of Life Expectancy for Brazil
# Bar chart of Life Expectancy for South American countries in 2020
# Update layout to add a title and hide the legend
```
## Walkthrough #8: Creating a Dynamic Data Report
### Selecting relevant data
```{python}
# Select relevant data for the year 2020 and specific columns
selected_data = economies[economies['year'] == 2020][['code', 'gdp_percapita', 'gross_savings', 'inflation_rate', 'income_group']]
selected_data.head()
```
### Building a dynamic report
```{python}
# Create a subplot figure with 3 rows
fig = make_subplots(rows=3, cols=1,
subplot_titles=('GDP Per Capita vs. Gross Savings',
'GDP Per Capita by Country and Income Group',
'Gross Savings by Country and Income Group'))
# Add scatter plot
fig.add_trace(go.Scatter(x=selected_data['gdp_percapita'], y=selected_data['gross_savings'],
mode='markers',
marker=dict(color=selected_data['income_group'].astype('category').cat.codes),
text=selected_data['code'], name='Scatter'),
row=1, col=1)
# Add bar chart
fig.add_trace(go.Bar(x=selected_data['code'], y=selected_data['gdp_percapita'],
marker=dict(color=selected_data['income_group'].astype('category').cat.codes), name='Bar'),
row=2, col=1)
# Add another scatter plot
fig.add_trace(go.Scatter(x=selected_data['code'], y=selected_data['gross_savings'],
mode='markers',
marker=dict(color=selected_data['income_group'].astype('category').cat.codes), text=selected_data['code'], name='Scatter'),
row=3, col=1)
# Update layout
fig.update_layout(title_text='Dynamic Data Report for Economic Indicators (2020)', showlegend=False, height=900)
fig.show()
```
### Adding contextual text and summaries
```{python}
import plotly.io as pio
import plotly.graph_objects as go
# Create a subplot figure with 3 rows
fig = make_subplots(rows=3, cols=1,
subplot_titles=('GDP Per Capita vs. Gross Savings',
'GDP Per Capita by Country and Income Group',
'Gross Savings by Country and Income Group'))
# Add scatter plot
fig.add_trace(go.Scatter(x=selected_data['gdp_percapita'], y=selected_data['gross_savings'],
mode='markers',
marker=dict(color=selected_data['income_group'].astype('category').cat.codes),
text=selected_data['code'], name='Scatter'),
row=1, col=1)
# Add bar chart
fig.add_trace(go.Bar(x=selected_data['code'], y=selected_data['gdp_percapita'],
marker=dict(color=selected_data['income_group'].astype('category').cat.codes), name='Bar'),
row=2, col=1)
# Add another scatter plot
fig.add_trace(go.Scatter(x=selected_data['code'], y=selected_data['gross_savings'],
mode='markers',
marker=dict(color=selected_data['income_group'].astype('category').cat.codes),
text=selected_data['code'], name='Scatter'),
row=3, col=1)
# Update layout
fig.update_layout(
title_text='Dynamic Data Report for Economic Indicators (2020)',
showlegend=False,
height=900,
annotations=[
go.layout.Annotation(
text='''This report presents key economic indicators for various countries in 2020, categorized by income group. ''',
xref='paper', yref='paper', x=0.5, y=1, showarrow=False, font=dict(size=14)
)
]
)
# Add summaries below each subplot
fig.add_annotation(text='The scatter plot reveals a positive correlation between GDP per Capita and Gross Savings, especially for high-income countries.', xref='paper', yref='paper', x=0, y=0.75, showarrow=False, font=dict(size=12))
fig.add_annotation(text='The bar chart shows that high-income countries generally have higher GDP per Capita compared to low-income countries.', xref='paper', yref='paper', x=0, y=0.30, showarrow=False, font=dict(size=12))
fig.add_annotation(text='The scatter plot indicates no clear relationship between income group and gross savings.', xref='paper', yref='paper', x=0, y=-0.1, showarrow=False, font=dict(size=12))
fig.show()
```
## Exercise #8: Creating a Dynamic Data Report
By completing this exercise, you will be able to use `pandas` and `plotly` to
- Select relevant data
- Build a dynamic report
- Add contextual text and summaries