.ipynb
file extension (e.g., my_notebook.ipynb
).A Jupyter notebook can be run in one of the following Jupyter environments.
The first two environments require installations on your local machine or a server. We will use Google Colab as you can run it inside a cloud environment.
Every cell in a Jupyter notebook is of a specific type. The list of supported types vary by Jupyter environment.
Google Colab supports two types of cells.
The cell below is a code cell. It contains a block of executable code.
Run the code below by clicking on the cell below and clicking the "Run" icon (▶).
print(10 + 20)
▶️ Run the code cell below to import unittest
, a module used for 🧭 Check Your Work sections and the autograder.
import unittest
tc = unittest.TestCase()
my_list = [11, 20, 52, 91, 90, 75, 74, 20, 21, 10, 14]
### BEGIN SOLUTION
result = 0
for num in my_list:
result = result + num
### END SOLUTION
print(result)
478
# Challenge 1 Autograder
import unittest
tc = unittest.TestCase()
tc.assertEqual(result, 478)
Pandas is a Python library for data manipulation and analysis. Although it's used universally in data-related programming applications, it was initially developed for financial analysis by AQR Capital Management.
Note: A library in the context of programming is a collection of functions (and other data) that others have already written for you.
Pandas is popular for many reasons:
### BEGIN SOLUTION
import pandas as pd
import numpy as np
### END SOLUTION
# Challenge 2 Autograder
import sys
tc.assertTrue("pd" in globals(), "Check whether you have correctly import Pandas with an alias.")
tc.assertTrue("np" in globals(), "Check whether you have correctly import NumPy with an alias.")
Series
...¶The basic building block of Pandas is a Series
. A Series
is like a list, but with many more features.
You can create a Series
by passing a list of values to pd.Series()
.
s = pd.Series([1, 2, 3, np.nan, 5, 6])
s
0 1.0 1 2.0 2 3.0 3 NaN 4 5.0 5 6.0 dtype: float64
my_list = [1, 2, 3, 4]
print(type(my_list))
display(my_list * 2)
<class 'list'>
[1, 2, 3, 4, 1, 2, 3, 4]
my_series = pd.Series([1, 2, 3, 4])
print(type(my_series))
display(my_series * 2)
<class 'pandas.core.series.Series'>
0 2 1 4 2 6 3 8 dtype: int64
What happens when you multiply a Python list
by number 2
? It repeats the elements.
How about a Series
? It multiples each element by 2
!
### BEGIN SOLUTION
my_series = pd.Series([10, 20, 30])
### END SOLUTION
my_series
0 10 1 20 2 30 dtype: int64
# Challenge 2 Autograder
pd.testing.assert_series_equal(my_series, pd.Series([1, 2, 3]) * 10)
Series
methods¶A pandas Series
is similar to a Python list
. However, a Series
provides many methods (equivalent to functions) for you to use.
As an example, num_reviews.mean()
will return the average number of reviews.
reviews_count = [12715, 2274, 2771, 3952, 528, 2766, 724]
num_reviews = pd.Series(reviews_count)
print(num_reviews)
0 12715 1 2274 2 2771 3 3952 4 528 5 2766 6 724 dtype: int64