Lecture 8: August 23nd, 2023#

Check-in Question: Happy Wednesday! Would you rather be able to fly at 10mph, or run at 100mph?

Updates and Reminders:

  • Homework 3 and Homework 4 due tonight at midnight.

  • Homework 5 and Homework 6 will be posted tonight. They are due Wednesday, Week 4 at midnight.

  • Extra attempts should have been added for last week’s outcome quizzes. If you did not get credit for an outcome quiz last week, you have 2 extra attempts this week. Let me know if these attempts are not showing up.

  • I am still working on getting new outcome quizzes up. I’ll make an announcement when they are live.

Today:

  • Last EDA lecture! We’ll go through some important python concepts (f-strings, lambda functions, list comprehension). This is part of what’s called pythonic code.

Overall Question#

  • From 2002 to 2008, how did the unemployment rate change across different industries?

For each of 14 industries, we will write one sentence briefly addressing this question.

Preparing the Data#

  • Load the attached unemployment.csv file as a pandas DataFrame df.

  • Convert the “date” column to a datetime dtype, by using pd.to_datetime. (Make sure you’ve actually replaced the “date” column, as opposed to displaying a new Series and leaving df the same.)

  • Add a “year” column to df using the dt accessor.

import pandas as pd
df = pd.read_csv("unemployment.csv")
df.shape
(1708, 3)
df.sample(5)
industry date rate
852 Information 2010-01-01 08:00:00+00:00 10.0
1120 Education and Health 2001-11-01 08:00:00+00:00 3.1
1661 Self-employed 2006-04-01 08:00:00+00:00 3.1
327 Construction 2006-12-01 08:00:00+00:00 6.9
1436 Other 2007-11-01 07:00:00+00:00 4.1
df["industry"].unique()
array(['Government', 'Mining and Extraction', 'Construction',
       'Manufacturing', 'Wholesale and Retail Trade',
       'Transportation and Utilities', 'Information', 'Finance',
       'Business services', 'Education and Health',
       'Leisure and hospitality', 'Other', 'Agriculture', 'Self-employed'],
      dtype=object)
len(df["industry"].unique())
14

Let’s convert the date column to a datetime dtype.

#have I actually changed the column?
#no!
pd.to_datetime(df["date"])
0      2000-01-01 08:00:00+00:00
1      2000-02-01 08:00:00+00:00
2      2000-03-01 08:00:00+00:00
3      2000-04-01 08:00:00+00:00
4      2000-05-01 07:00:00+00:00
                  ...           
1703   2009-10-01 07:00:00+00:00
1704   2009-11-01 07:00:00+00:00
1705   2009-12-01 08:00:00+00:00
1706   2010-01-01 08:00:00+00:00
1707   2010-02-01 08:00:00+00:00
Name: date, Length: 1708, dtype: datetime64[ns, UTC]
df["date"] = pd.to_datetime(df["date"])
df
industry date rate
0 Government 2000-01-01 08:00:00+00:00 2.1
1 Government 2000-02-01 08:00:00+00:00 2.0
2 Government 2000-03-01 08:00:00+00:00 1.5
3 Government 2000-04-01 08:00:00+00:00 1.3
4 Government 2000-05-01 07:00:00+00:00 1.9
... ... ... ...
1703 Self-employed 2009-10-01 07:00:00+00:00 5.9
1704 Self-employed 2009-11-01 07:00:00+00:00 5.7
1705 Self-employed 2009-12-01 08:00:00+00:00 5.9
1706 Self-employed 2010-01-01 08:00:00+00:00 7.2
1707 Self-employed 2010-02-01 08:00:00+00:00 6.5

1708 rows Ă— 3 columns

Now, let’s add a “year” column

df["year"] = df["date"].dt.year
df
industry date rate year
0 Government 2000-01-01 08:00:00+00:00 2.1 2000
1 Government 2000-02-01 08:00:00+00:00 2.0 2000
2 Government 2000-03-01 08:00:00+00:00 1.5 2000
3 Government 2000-04-01 08:00:00+00:00 1.3 2000
4 Government 2000-05-01 07:00:00+00:00 1.9 2000
... ... ... ... ...
1703 Self-employed 2009-10-01 07:00:00+00:00 5.9 2009
1704 Self-employed 2009-11-01 07:00:00+00:00 5.7 2009
1705 Self-employed 2009-12-01 08:00:00+00:00 5.9 2009
1706 Self-employed 2010-01-01 08:00:00+00:00 7.2 2010
1707 Self-employed 2010-02-01 08:00:00+00:00 6.5 2010

1708 rows Ă— 4 columns

Using df.groupby and a for-loop#

Overview of our setup: We’ll first go through the problem statement and talk about what the problem is asking for. We’ll then break the problem into smaller pieces and better under df.groupby objects before formally writing out a solution.

GroupBy objects can be pretty mysterious. The point of these problems is to get more comfortable with them.

(There are other solutions possible, but the point of this lecture is to practice iterating over a pandas GroupBy object.)

There are 14 total industries in the dataset. Here are two examples of the sentences we want to produce. Notice how in one of the sentences we use the word “increased” and in the other sentence we use the word “decreased”. Notice also that each of our numbers shows two decimal places.

From 2002 to 2008, the median unemployment rate in Leisure and hospitality increased by 2.94%, from 8.50 to 8.75.

From 2002 to 2008, the median unemployment rate in Manufacturing decreased by 18.18%, from 6.60 to 5.40.

  • Take a minute to understand these computations. For example, do you see why we are saying 8.50 to 8.75 is an increase of 2.94%?

Note: I’m not worried about the sign of this number. We’ll take care of it when we code the solution to the problem. Formula for percent change: $\( \frac{x_{\text{new}}-x_{\text{old}}}{x_{\text{old}}} \times 100 \)$

Let’s do a sanity check computation:

((8.75-8.5)/8.5)*100
2.941176470588235
  • For each of the 14 industries, append the corresponding sentence to text_list. Use the following template.

Before we solve this problem, we’ll go over a few related concepts.

Note for those reading this after the lecture. We built this code slowly after trying the examples below.

  • Make sure you understand the logic of this skeleton, even if you don’t understand all the individual parts yet.

text_list = []
for ???, ??? in df.groupby(???):
    ??? (as many lines as you need)
    change = ??? if ??? else ??? # "increased" or "decreased" as appropriate
    sentence = f'''From {years[0]} to {years[1]}, the median unemployment rate in {???} {change} by {???:.2%}, from {???:.2f} to {???:.2f}.'''
    text_list.append(sentence)

What we solved after the df.groupby practice#

What do you think we should organized our data based on? The chat has answered: For this problem, it makes sense for us to sort by “industry”.

Notes from building this code together:

  • In the tuple unpacking below, the first variable gives industry, and the second variable gives the sub-DataFrame corresponding to that industry.

  • How will I know if the median unemployment rate increased or decreased? If median_2002 < median_2008, then we can say that the rate increased.

years = [2002,2008]
text_list = []
for ind_name,sub_df in df.groupby("industry"):
    #let's get the median unemployment rate for these two years
    median_2002 = sub_df[sub_df["year"] == years[0]]["rate"].median()
    median_2008 = sub_df[sub_df["year"] == years[1]]["rate"].median()
    change = "increased" if median_2002 < median_2008 else "decreased" # "increased" or "decreased" as appropriate
    #I know that no values stayed fixed in this data, so let's not worry about if the rate is equal

What we solved after the f-strings practice#

years = [2002,2008]
text_list = []
for ind_name,sub_df in df.groupby("industry"):
    #let's get the median unemployment rate for these two years
    median_2002 = sub_df[sub_df["year"] == years[0]]["rate"].median()
    median_2008 = sub_df[sub_df["year"] == years[1]]["rate"].median()
    change = "increased" if median_2002 < median_2008 else "decreased" # "increased" or "decreased" as appropriate
    #I know that no values stayed fixed in this data, so let's not worry about if the rate is equal
    sentence = f'''From {years[0]} to {years[1]}, the median unemployment rate in {ind_name} {change} by {abs((median_2008-median_2002)/(median_2002)):.2%}, from {median_2002:.2f} to {median_2008:.2f}.'''
    text_list.append(sentence)
text_list
['From 2002 to 2008, the median unemployment rate in Agriculture decreased by 9.04%, from 9.40 to 8.55.',
 'From 2002 to 2008, the median unemployment rate in Business services decreased by 18.71%, from 7.75 to 6.30.',
 'From 2002 to 2008, the median unemployment rate in Construction increased by 34.57%, from 8.10 to 10.90.',
 'From 2002 to 2008, the median unemployment rate in Education and Health increased by 9.37%, from 3.20 to 3.50.',
 'From 2002 to 2008, the median unemployment rate in Finance increased by 2.82%, from 3.55 to 3.65.',
 'From 2002 to 2008, the median unemployment rate in Government decreased by 4.08%, from 2.45 to 2.35.',
 'From 2002 to 2008, the median unemployment rate in Information decreased by 29.58%, from 7.10 to 5.00.',
 'From 2002 to 2008, the median unemployment rate in Leisure and hospitality increased by 2.94%, from 8.50 to 8.75.',
 'From 2002 to 2008, the median unemployment rate in Manufacturing decreased by 18.18%, from 6.60 to 5.40.',
 'From 2002 to 2008, the median unemployment rate in Mining and Extraction decreased by 47.24%, from 6.35 to 3.35.',
 'From 2002 to 2008, the median unemployment rate in Other increased by 3.00%, from 5.00 to 5.15.',
 'From 2002 to 2008, the median unemployment rate in Self-employed increased by 28.85%, from 2.60 to 3.35.',
 'From 2002 to 2008, the median unemployment rate in Transportation and Utilities increased by 7.29%, from 4.80 to 5.15.',
 'From 2002 to 2008, the median unemployment rate in Wholesale and Retail Trade decreased by 3.25%, from 6.15 to 5.95.']

Itearting through df.groupby objects#

We’ve seen examples of calling methods on GroupBy objects, but how could we iterate through a GroupBy object? What does it even look like?

  • Recall, we’ve seen df.groupby with the mpg dataset. Here’s a quick refresher of how we used it.

import seaborn as sns
mpg = sns.load_dataset("mpg")
mpg.groupby("origin").median()
mpg cylinders displacement horsepower weight acceleration model_year
origin
europe 26.5 4 104.5 76.5 2240 15.7 76
japan 31.6 4 97.0 75.0 2155 16.4 78
usa 18.5 6 250.0 105.0 3365 15.0 76

Maybe you feel that GroupBy is a little mysterious? We’ve seen examples of calling methods on this object, but what does the object itself actually look like?

  • For example, if we think of list objects, we know the general shape of a list. Similar for things like dictionaries, tuples, sets, etc.

mpg.groupby("origin")
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x7fc9ab672490>

Let’s start by looking at an example taken from this link. This is good advice for math in general: we’re going to start with a much easier example before we use our ideas to solve the more complicated problem.

my_dict = {'X': ['A', 'B', 'A', 'B'],
        'Y': [1, 4, 3, 2]}
my_dict
{'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]}
  • Convert my_dict to a pandas DataFrame by using the pandas function DataFrame. Call the result df.

df = pd.DataFrame(my_dict)
df
X Y
0 A 1
1 B 4
2 A 3
3 B 2
  • Use groupby to group df by “X”. Call the result df_groups.

df_groups = df.groupby("X")
df_groups
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x7fc9bef54eb0>
  • Iterate through df_groups using a for-loop. For each iteration, print the following to get a feel for what the objects look like:

    • The data type of the returned object

    • The length of each object

    • The 0th element of each object, the 1st element of each object, etc.

    • name of the group along with the sub-DataFrame belonging to that group. Can you predict how many times we will go through the for-loop, based on our sample data?

for unknown in df_groups:
    print(type(unknown))
<class 'tuple'>
<class 'tuple'>

Maybe this is strange? If we iterate through df_groups, we see that the objects are tuples. The next natural question to ask is how long is each tuple?

for tup in df_groups:
    print(len(tup))
2
2

Now we know that each tuple is length 2. Maybe now we want to ask what is each element?

#print the 0th element of each tuple
for tup in df_groups:
    print(tup[0])
    print(type(tup[0]))
A
<class 'str'>
B
<class 'str'>

Big Reminder: We’re grouping df by “X”, so we sort based on what values appear in the “X” column.

df
X Y
0 A 1
1 B 4
2 A 3
3 B 2
#print the 1st element of each tuple
for tup in df_groups:
    print(tup[1])
    print(type(tup[1]))
   X  Y
0  A  1
2  A  3
<class 'pandas.core.frame.DataFrame'>
   X  Y
1  B  4
3  B  2
<class 'pandas.core.frame.DataFrame'>
#example of tuple unpacking
#split the tuple into two variables
for group_name,sub_data in df_groups:
    print("The name of the group is: {group_name}")
    print(sub_data)
The name of the group is: {group_name}
   X  Y
0  A  1
2  A  3
The name of the group is: {group_name}
   X  Y
1  B  4
3  B  2
#example of tuple unpacking
#split the tuple into two variables
#we also use f-strings to format
for group_name,sub_data in df_groups:
    print(f"The name of the group is: {group_name}")
    print(sub_data)
The name of the group is: A
   X  Y
0  A  1
2  A  3
The name of the group is: B
   X  Y
1  B  4
3  B  2
df
X Y
0 A 1
1 B 4
2 A 3
3 B 2

Observations:

Recall df_groups sorts the data by “X” values. When we iterate through df_groups, we get tuples where the 0th entry represents a value of “X”, and the 1st entry represent the sub-DataFrame of df where all the “X” values are equal to what’s in position 0.

f-strings#

Before we try the above problem, let’s see some examples with f-strings and string formatting.

f-strings stands for “format”-strings, and gives us a nice way of passing variables to strings. These are relatively new to Python, and all new code should use them over the older methods. However, if you’re reading older code, you might see strings formatted in a different way.

See this link for f-string formatting options.

  • Import NumPy and instantiate a random number generator object.

import numpy as np
rng = np.random.default_rng()
  • Make a length 100 NumPy array of random real numbers between 0 and 1. Call it arr. Iterate through this array by using n,x in enumerate(arr)

Random real number n of 100: x

Let’s see a quick example with enumerate, just to get an idea of what’s going on.

mylist = ["Math","10","is","fun"]
tuple(enumerate(mylist))
((0, 'Math'), (1, '10'), (2, 'is'), (3, 'fun'))
arr = rng.random(100)
arr
array([0.11061944, 0.11971732, 0.51584006, 0.93752867, 0.35111516,
       0.06131185, 0.09821899, 0.8774908 , 0.35969537, 0.62616258,
       0.20882721, 0.712709  , 0.97449263, 0.25337044, 0.39065286,
       0.11799469, 0.24675555, 0.93237665, 0.31145551, 0.90083411,
       0.15264816, 0.52653361, 0.80022298, 0.35194885, 0.84784714,
       0.19087755, 0.5073576 , 0.40609193, 0.65189288, 0.39712484,
       0.50550007, 0.46032286, 0.68185156, 0.28514403, 0.66728911,
       0.92148533, 0.29082687, 0.9916658 , 0.12693194, 0.23387831,
       0.27393358, 0.89232009, 0.21735429, 0.9590574 , 0.39393877,
       0.8303353 , 0.31105577, 0.49755744, 0.74967545, 0.30198071,
       0.04722153, 0.00191545, 0.76268025, 0.53916591, 0.63031923,
       0.48364106, 0.41997953, 0.1651973 , 0.22841607, 0.74006554,
       0.5052115 , 0.30802897, 0.59875349, 0.67724492, 0.66261512,
       0.94554117, 0.33483388, 0.12114549, 0.77081538, 0.58261255,
       0.59780005, 0.08002206, 0.90802392, 0.01513321, 0.75608469,
       0.71962624, 0.24301018, 0.85917039, 0.87785795, 0.88106731,
       0.27116972, 0.85644604, 0.05011955, 0.72560078, 0.92612154,
       0.1934866 , 0.53331864, 0.77483657, 0.10111687, 0.4731246 ,
       0.13572267, 0.74192126, 0.86060337, 0.05773144, 0.70237882,
       0.43530201, 0.08521461, 0.66498441, 0.12722077, 0.98731562])
#This will print the same sentence 100 times
for index,value in enumerate(arr):
    print("Random real number index of 100: value")
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
Random real number index of 100: value
for index,value in enumerate(arr):
    print(f"Random real number {index} of 100: {value}")
Random real number 0 of 100: 0.11061943524068973
Random real number 1 of 100: 0.11971732485622055
Random real number 2 of 100: 0.5158400614424339
Random real number 3 of 100: 0.9375286698013243
Random real number 4 of 100: 0.35111516277129606
Random real number 5 of 100: 0.061311848724520446
Random real number 6 of 100: 0.09821899481995111
Random real number 7 of 100: 0.8774907970493565
Random real number 8 of 100: 0.3596953703889514
Random real number 9 of 100: 0.6261625787706582
Random real number 10 of 100: 0.20882720643638852
Random real number 11 of 100: 0.7127090047945163
Random real number 12 of 100: 0.9744926283748068
Random real number 13 of 100: 0.2533704421394394
Random real number 14 of 100: 0.39065286278730493
Random real number 15 of 100: 0.11799469115066674
Random real number 16 of 100: 0.246755552348788
Random real number 17 of 100: 0.9323766483077076
Random real number 18 of 100: 0.31145550967666835
Random real number 19 of 100: 0.9008341091813429
Random real number 20 of 100: 0.15264815793726805
Random real number 21 of 100: 0.5265336064828982
Random real number 22 of 100: 0.8002229773873952
Random real number 23 of 100: 0.3519488524819323
Random real number 24 of 100: 0.8478471423770868
Random real number 25 of 100: 0.19087755321968902
Random real number 26 of 100: 0.5073576012641755
Random real number 27 of 100: 0.40609193207627503
Random real number 28 of 100: 0.6518928782723821
Random real number 29 of 100: 0.3971248409693866
Random real number 30 of 100: 0.505500068084574
Random real number 31 of 100: 0.46032286114767074
Random real number 32 of 100: 0.6818515588460832
Random real number 33 of 100: 0.28514402749920964
Random real number 34 of 100: 0.6672891103301868
Random real number 35 of 100: 0.9214853277586431
Random real number 36 of 100: 0.2908268687128236
Random real number 37 of 100: 0.991665800404907
Random real number 38 of 100: 0.126931941959605
Random real number 39 of 100: 0.23387831017673177
Random real number 40 of 100: 0.27393358223615394
Random real number 41 of 100: 0.8923200888783408
Random real number 42 of 100: 0.21735428507237686
Random real number 43 of 100: 0.9590573991384616
Random real number 44 of 100: 0.39393877066125826
Random real number 45 of 100: 0.8303353000002976
Random real number 46 of 100: 0.31105577053295697
Random real number 47 of 100: 0.49755743721630175
Random real number 48 of 100: 0.7496754470305963
Random real number 49 of 100: 0.30198071476106425
Random real number 50 of 100: 0.04722153370872084
Random real number 51 of 100: 0.0019154499313072115
Random real number 52 of 100: 0.7626802516852722
Random real number 53 of 100: 0.5391659137498794
Random real number 54 of 100: 0.630319232569699
Random real number 55 of 100: 0.4836410626643336
Random real number 56 of 100: 0.4199795278367444
Random real number 57 of 100: 0.16519729729017207
Random real number 58 of 100: 0.22841606763974898
Random real number 59 of 100: 0.7400655361152653
Random real number 60 of 100: 0.5052115031303246
Random real number 61 of 100: 0.308028969748275
Random real number 62 of 100: 0.5987534868334323
Random real number 63 of 100: 0.6772449202083302
Random real number 64 of 100: 0.662615115506966
Random real number 65 of 100: 0.9455411712290154
Random real number 66 of 100: 0.33483387965474254
Random real number 67 of 100: 0.12114548964687544
Random real number 68 of 100: 0.7708153826356782
Random real number 69 of 100: 0.5826125456551934
Random real number 70 of 100: 0.5978000451055865
Random real number 71 of 100: 0.08002205955880004
Random real number 72 of 100: 0.908023917431064
Random real number 73 of 100: 0.015133210775007622
Random real number 74 of 100: 0.7560846885247896
Random real number 75 of 100: 0.7196262390043356
Random real number 76 of 100: 0.24301018494422555
Random real number 77 of 100: 0.8591703872048005
Random real number 78 of 100: 0.8778579536558972
Random real number 79 of 100: 0.8810673136196642
Random real number 80 of 100: 0.2711697184115476
Random real number 81 of 100: 0.856446039511476
Random real number 82 of 100: 0.05011955016294256
Random real number 83 of 100: 0.7256007781553699
Random real number 84 of 100: 0.9261215443901151
Random real number 85 of 100: 0.19348660241512317
Random real number 86 of 100: 0.5333186404044601
Random real number 87 of 100: 0.774836572516208
Random real number 88 of 100: 0.10111687469125386
Random real number 89 of 100: 0.4731246015831304
Random real number 90 of 100: 0.13572267235154045
Random real number 91 of 100: 0.7419212566014083
Random real number 92 of 100: 0.8606033730449978
Random real number 93 of 100: 0.0577314422832228
Random real number 94 of 100: 0.7023788152651673
Random real number 95 of 100: 0.4353020087719637
Random real number 96 of 100: 0.0852146123516655
Random real number 97 of 100: 0.6649844129777946
Random real number 98 of 100: 0.12722076673121585
Random real number 99 of 100: 0.9873156174279234
  • Use f-strings and string formatting to print the corresponding versions of this sentence:

Percent chance that Math 10 is fun today: x.yz%

for index,value in enumerate(arr):
    print(f"Percent chance that Math 10 is fun on day {index} of 100: {value:.2%}")
Percent chance that Math 10 is fun on day 0 of 100: 11.06%
Percent chance that Math 10 is fun on day 1 of 100: 11.97%
Percent chance that Math 10 is fun on day 2 of 100: 51.58%
Percent chance that Math 10 is fun on day 3 of 100: 93.75%
Percent chance that Math 10 is fun on day 4 of 100: 35.11%
Percent chance that Math 10 is fun on day 5 of 100: 6.13%
Percent chance that Math 10 is fun on day 6 of 100: 9.82%
Percent chance that Math 10 is fun on day 7 of 100: 87.75%
Percent chance that Math 10 is fun on day 8 of 100: 35.97%
Percent chance that Math 10 is fun on day 9 of 100: 62.62%
Percent chance that Math 10 is fun on day 10 of 100: 20.88%
Percent chance that Math 10 is fun on day 11 of 100: 71.27%
Percent chance that Math 10 is fun on day 12 of 100: 97.45%
Percent chance that Math 10 is fun on day 13 of 100: 25.34%
Percent chance that Math 10 is fun on day 14 of 100: 39.07%
Percent chance that Math 10 is fun on day 15 of 100: 11.80%
Percent chance that Math 10 is fun on day 16 of 100: 24.68%
Percent chance that Math 10 is fun on day 17 of 100: 93.24%
Percent chance that Math 10 is fun on day 18 of 100: 31.15%
Percent chance that Math 10 is fun on day 19 of 100: 90.08%
Percent chance that Math 10 is fun on day 20 of 100: 15.26%
Percent chance that Math 10 is fun on day 21 of 100: 52.65%
Percent chance that Math 10 is fun on day 22 of 100: 80.02%
Percent chance that Math 10 is fun on day 23 of 100: 35.19%
Percent chance that Math 10 is fun on day 24 of 100: 84.78%
Percent chance that Math 10 is fun on day 25 of 100: 19.09%
Percent chance that Math 10 is fun on day 26 of 100: 50.74%
Percent chance that Math 10 is fun on day 27 of 100: 40.61%
Percent chance that Math 10 is fun on day 28 of 100: 65.19%
Percent chance that Math 10 is fun on day 29 of 100: 39.71%
Percent chance that Math 10 is fun on day 30 of 100: 50.55%
Percent chance that Math 10 is fun on day 31 of 100: 46.03%
Percent chance that Math 10 is fun on day 32 of 100: 68.19%
Percent chance that Math 10 is fun on day 33 of 100: 28.51%
Percent chance that Math 10 is fun on day 34 of 100: 66.73%
Percent chance that Math 10 is fun on day 35 of 100: 92.15%
Percent chance that Math 10 is fun on day 36 of 100: 29.08%
Percent chance that Math 10 is fun on day 37 of 100: 99.17%
Percent chance that Math 10 is fun on day 38 of 100: 12.69%
Percent chance that Math 10 is fun on day 39 of 100: 23.39%
Percent chance that Math 10 is fun on day 40 of 100: 27.39%
Percent chance that Math 10 is fun on day 41 of 100: 89.23%
Percent chance that Math 10 is fun on day 42 of 100: 21.74%
Percent chance that Math 10 is fun on day 43 of 100: 95.91%
Percent chance that Math 10 is fun on day 44 of 100: 39.39%
Percent chance that Math 10 is fun on day 45 of 100: 83.03%
Percent chance that Math 10 is fun on day 46 of 100: 31.11%
Percent chance that Math 10 is fun on day 47 of 100: 49.76%
Percent chance that Math 10 is fun on day 48 of 100: 74.97%
Percent chance that Math 10 is fun on day 49 of 100: 30.20%
Percent chance that Math 10 is fun on day 50 of 100: 4.72%
Percent chance that Math 10 is fun on day 51 of 100: 0.19%
Percent chance that Math 10 is fun on day 52 of 100: 76.27%
Percent chance that Math 10 is fun on day 53 of 100: 53.92%
Percent chance that Math 10 is fun on day 54 of 100: 63.03%
Percent chance that Math 10 is fun on day 55 of 100: 48.36%
Percent chance that Math 10 is fun on day 56 of 100: 42.00%
Percent chance that Math 10 is fun on day 57 of 100: 16.52%
Percent chance that Math 10 is fun on day 58 of 100: 22.84%
Percent chance that Math 10 is fun on day 59 of 100: 74.01%
Percent chance that Math 10 is fun on day 60 of 100: 50.52%
Percent chance that Math 10 is fun on day 61 of 100: 30.80%
Percent chance that Math 10 is fun on day 62 of 100: 59.88%
Percent chance that Math 10 is fun on day 63 of 100: 67.72%
Percent chance that Math 10 is fun on day 64 of 100: 66.26%
Percent chance that Math 10 is fun on day 65 of 100: 94.55%
Percent chance that Math 10 is fun on day 66 of 100: 33.48%
Percent chance that Math 10 is fun on day 67 of 100: 12.11%
Percent chance that Math 10 is fun on day 68 of 100: 77.08%
Percent chance that Math 10 is fun on day 69 of 100: 58.26%
Percent chance that Math 10 is fun on day 70 of 100: 59.78%
Percent chance that Math 10 is fun on day 71 of 100: 8.00%
Percent chance that Math 10 is fun on day 72 of 100: 90.80%
Percent chance that Math 10 is fun on day 73 of 100: 1.51%
Percent chance that Math 10 is fun on day 74 of 100: 75.61%
Percent chance that Math 10 is fun on day 75 of 100: 71.96%
Percent chance that Math 10 is fun on day 76 of 100: 24.30%
Percent chance that Math 10 is fun on day 77 of 100: 85.92%
Percent chance that Math 10 is fun on day 78 of 100: 87.79%
Percent chance that Math 10 is fun on day 79 of 100: 88.11%
Percent chance that Math 10 is fun on day 80 of 100: 27.12%
Percent chance that Math 10 is fun on day 81 of 100: 85.64%
Percent chance that Math 10 is fun on day 82 of 100: 5.01%
Percent chance that Math 10 is fun on day 83 of 100: 72.56%
Percent chance that Math 10 is fun on day 84 of 100: 92.61%
Percent chance that Math 10 is fun on day 85 of 100: 19.35%
Percent chance that Math 10 is fun on day 86 of 100: 53.33%
Percent chance that Math 10 is fun on day 87 of 100: 77.48%
Percent chance that Math 10 is fun on day 88 of 100: 10.11%
Percent chance that Math 10 is fun on day 89 of 100: 47.31%
Percent chance that Math 10 is fun on day 90 of 100: 13.57%
Percent chance that Math 10 is fun on day 91 of 100: 74.19%
Percent chance that Math 10 is fun on day 92 of 100: 86.06%
Percent chance that Math 10 is fun on day 93 of 100: 5.77%
Percent chance that Math 10 is fun on day 94 of 100: 70.24%
Percent chance that Math 10 is fun on day 95 of 100: 43.53%
Percent chance that Math 10 is fun on day 96 of 100: 8.52%
Percent chance that Math 10 is fun on day 97 of 100: 66.50%
Percent chance that Math 10 is fun on day 98 of 100: 12.72%
Percent chance that Math 10 is fun on day 99 of 100: 98.73%

Go back to the original question about the unemployment dataset now! We are ready to tackle it!

Plotting charts#

  • Using the same dataset, now group df by “Industry”. Call this object df_ind

df_ind = df.groupby("industry")
import altair as alt
def make_chart(df_sub):
    chart = alt.Chart(df_sub).mark_line().encode(
        x="year:N",
        y="median(rate)",
        tooltip=["year","median(rate)"]
    )
    return chart+chart.mark_circle()
make_chart(df_ind.get_group("Manufacturing"))
  • Write a function make_chart which takes as input a DataFrame of df_ind, and as output returns a chart that looks like the following:

  • Using list comprehension, create a list of charts by using make_chart applied to each industry in df_ind. Use f-strings and .property(title=) to give each chart a title telling us which industry is being represented. Call this list chart_list.

#list of charts without titles
chart_list0 = [make_chart(sub_df) for ind_name,sub_df in df_ind]

Recall that the make_chart function returns a chart, which means that we can directly edit properties of the resulting chart.

chart_list = [make_chart(sub_df).properties(title=f"Industry: {ind_name}") for ind_name,sub_df in df_ind]
  • Apply the Altair function vconcat to chart_list. You’ll need to unpack char_list using *.

#without the titles
alt.vconcat(*chart_list0)
#with the titles 
alt.vconcat(*chart_list)

Practice with the DataFrame method apply and lambda functions#

  • Load the “taxis” dataset from Seaborn and drop rows with missing values.

import seaborn as sns
taxis = sns.load_dataset("taxis")
taxis.sample(5)
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough
102 2019-03-01 07:34:30 2019-03-01 07:40:58 1 1.20 6.5 0.0 0.0 9.8 yellow cash Bloomingdale Upper West Side North Manhattan Manhattan
4783 2019-03-05 00:26:11 2019-03-05 00:30:29 1 0.75 5.0 1.0 0.0 9.8 yellow credit card Midtown North Lincoln Square West Manhattan Manhattan
5222 2019-03-18 12:21:39 2019-03-18 12:29:11 5 0.67 6.0 3.0 0.0 12.3 yellow credit card Upper East Side South Central Park Manhattan Manhattan
3127 2019-03-02 20:35:28 2019-03-02 20:49:47 1 4.23 14.0 0.0 0.0 15.3 yellow cash LaGuardia Airport Long Island City/Queens Plaza Queens Queens
144 2019-03-23 18:35:01 2019-03-23 18:47:39 1 3.20 12.5 2.0 0.0 17.8 yellow credit card UN/Turtle Bay South East Village Manhattan Manhattan
  • As a warm-up with apply, try applying the len function using first axis=0 and then axis=1. We’ll see more serious uses below.

taxis.shape
(6433, 14)
taxis.apply(len, axis=0)
pickup             6433
dropoff            6433
passengers         6433
distance           6433
fare               6433
tip                6433
tolls              6433
total              6433
color              6433
payment            6433
pickup_zone        6433
dropoff_zone       6433
pickup_borough     6433
dropoff_borough    6433
dtype: int64
taxis.apply(len, axis=1)
0       14
1       14
2       14
3       14
4       14
        ..
6428    14
6429    14
6430    14
6431    14
6432    14
Length: 6433, dtype: int64

Let’s see an example now where the values will be different for different columns.

taxis.apply(lambda x: x.dtype, axis=0)
pickup             datetime64[ns]
dropoff            datetime64[ns]
passengers                  int64
distance                  float64
fare                      float64
tip                       float64
tolls                     float64
total                     float64
color                      object
payment                    object
pickup_zone                object
dropoff_zone               object
pickup_borough             object
dropoff_borough            object
dtype: object
  • Write a function has_airport which takes as input a row from df (not a row label but an entire row) and as output returns True if the “pickup_zone” or “dropoff_zone” entry contains the substring “Airport”.

  • Make a new column “Airport0” which contains True if the “pickup_zone” or “dropoff_zone” contains the substring “Airport”, and otherwise contains False. Use the has_airport function and df.apply(???, axis=???).

  • Make a column “Airport1” with the same values, again using apply, but this time using a lambda function.

  • Notice that df[["pickup_zone", "dropoff_zone"]] is a DataFrame containing just those two columns we’re interested in. Use apply this time to apply a lambda function to the columns rather than the rows, then use any. Name the result “Airport2”.

Created in deepnote.com Created in Deepnote