CSE 163
Section AX
TA1 & TA2
QOTD (sample): If you were a data structure, which one would you be and why?
Housekeeping 🏡
Important Dates and Reminders
All submissions are done through Gradescope
Recap
What we’ve Learned so far:
Game Plan
What We’ll Cover Today
List
Use Cases:
new_list = list()
new_list = []
new_list.append("a") # ["a"]
new_list.append(2) # ["a", 2]
new_list[0] # "a"
new_list.extend(["b"])
# ["a", 2, "b"]
new_list.remove("b")
# ["a", 2]
new_list.pop(0) # returns “a”
# new_list = [2]
Tuple
Use Cases:
tup = ("hello", "world")
tup[0] # "hello"
# takes in params a and b
def pack(a, b):
# returns a tuple of (a, b)
return a, b
Sets
- → difference (in THA2!)
Use Cases:
my_set = set()
my_set.add(10) # {10}
my_set.add(30) # {10, 30}
my_set.add(30) # {10, 30}
my_set.add([]) # Error!
if 10 in my_set: # Membership Query
print("Found 10!")
Dictionaries
Use Cases:
d = dict()
d = {} # same symbol as sets!
d['Triangle'] = 3
d['Square'] = 4
d['Square'] # 4
things = ["cat", "hat", "bat", "cat"]
my_dict = dict()
for i in things: # also really fast!
if i not in my_dict:
my_dict[i] = 0
my_dict[i] += 1
my_dict
# {"cat": 2, "hat": 1, "bat": 1}
File Processing
file_path = "home/doggies.txt"
with open(file_path) as f:
lines = f.readlines()
for l in lines:
print(l)
file_path = "home/doggies.txt"
with open(file_path) as f:
lines = f.readlines()
for l in lines:
words = l.split()
for w in words:
print(w)
10
Practice Problem
Solution
DataFrames Review
Data
Goal: Represent real-world phenomena in a tabular format
CSV
# cats.csv
import pandas as pd
data = pd.read_csv("cats.csv")
print(data)
===============================
name color age outdoor
0 fluffy ginger 2 True
1 sparky grey 8 False
2 storm black 1 True
===============================
# cats.csv in a list of dicts
cats = [
{"name": "fluffy", "age": 2},
{"name": "sparky", "age": 8},
{"name": "storm", "age": 1}
Processing:
List of dicts
# cats.csv in a list of dicts
cats = [
{"name": "fluffy", "age": 2},
{"name": "sparky", "age": 8},
{"name": "storm", "age": 1}
]
total_age = 0
for c in cats:
# c stores a cat dictionary
# ex: {"name": __, "age": __}
age = c['age']
total_age += age
total_age # 11
DataFrames
import pandas as pd
data = pd.read_csv("cats.csv")
print(data)
===============================
name color age outdoor
0 fluffy ginger 2 True
1 sparky grey 8 False
2 storm black 1 True
===============================
data['age'] # Series([2, 8, 1])
data['age'].sum() # 11
data['age'] * 4 # Series([8, 32, 4])
DataFrame Filtering
data['age'] > 1
# Series([True, True, False])
data[data['age'] > 1]
===============================
name color age outdoor
0 fluffy ginger 2 True
1 sparky grey 8 False
===============================
data['outdoor'] == True
# Series([True, False, True])
data[data['outdoor'] == True]
===============================
name color age outdoor
0 fluffy ginger 2 True
2 storm black 1 True
===============================
DataFrame Filtering
cont.
===============================
name color age outdoor
0 fluffy ginger 2 True
1 sparky grey 8 False
2 storm black 1 True
===============================
old_age = data['age'] > 1
# Series([True, True, False])
outdoors = data['outdoor'] == True
# Series([True, False, True])
old_age & outdoors
# Series([True, False, False])
data[old_age & outdoors]
===============================
name color age outdoor
0 fluffy ginger 2 True
===============================
DataFrame Indexing with .loc
df.loc[0] # same as df.loc[0, :]
# Series(["fluffy", "ginger", 2, True])
df.loc[0:1] # same as df.loc[0:1, :]
# DataFrame
===============================
name color age outdoor
0 fluffy ginger 2 True
1 sparky grey 8 False
===============================
df.loc[0:1, "color"]
# Series(["ginger", "grey"])
19
Practice problems!
Solutions
DF manipulation:
Warm-up
Groupby Demo
Group By
result = data.groupby('col1')['col2'].sum()
22
| col1 | col2 |
0 | A | 1 |
1 | B | 2 |
2 | C | 3 |
3 | A | 4 |
4 | C | 5 |
| col2 |
C | 3 |
5 |
| col2 |
B | 2 |
| col2 |
A | 1 |
4 |
A | 5 |
B | 2 |
C | 8 |
A | 5 |
B | 2 |
C | 8 |
Data�DataFrame
Split
Apply
Combine�Series
Groupby problems solutions
grouped_cities = gsb.groupby("CityOfOrigin")["FlavorScore"].idxmax()
# then, use the grouping from above as our row indexer in .loc (since we used idxmax()) and specify the other columns we want to display
gsb_grouped = gsb.loc[grouped_cities, ["Name", "CityOfOrigin", "FlavorScore"]]
city_year_count = gsb.groupby(["CityOfOrigin", "StartedBaking"]).size()
24
Section Code:
<section code>
Logistics & Reminders:
Remember you can come into office hours or post on Ed if you have any questions. Good luck and thanks for coming to section :)