Working with 2D Lists¶
In this exercise we're going to work with a 2D-list that you might recognize! It's the survey data from our first day.
I've taken the results of that survey and imported them into a 2D list (with a little bit of clean-up).
The first row is a list of headers that describe each column. Every row after that is one of the entries that was submitted.
To access rows or entries within rows, you can use indexes.
Examples¶
Access the header row (row 0
):
>> data[0]
['name',
'birthday',
'from',
'favorite_music',
'travel_dest',
'favorite_movie',
'favorite_planet',
'stay_age',
'be_animal',
'live_in',
'fictional_pet',
'super_power']
Access Mr. P's row (row 1
)
>> data[1]
['Mr. P',
'4/26',
'New Jersey',
'LCD Soundsystem',
'Brazil',
'The Truman Show',
'Venus',
28,
'Cat',
'Scadrial from Mistborn',
'War Horse from DnD',
'Slow Time']
Access Mr. P's name (row 1
, column 0
)
data[1][0]
'Mr. p'
Access what animal Mr. P would be (row 1
, column 8
):
data[1][8]
'Cat'
Assignment¶
Use for-loops to do the following analysis:
- Count how many entries are from
"New York"
- Print the names of everyone who put
"France"
or"Paris"
as their travel destination. - Calculate the average
"stay_age"
Extra Challeng 1
- Prompt the user for a column name, print the value for every entry for that column.
Extra Challenge 2
- Prompt the user for someon's name and the column you want to know about them. Print out the value for that name and column.
Input name: Mr. P
Input column: favorite_planet
Value is Venus
In [ ]:
Copied!
data = [
['name', 'birthday', 'from', 'favorite_music', 'travel_dest', 'favorite_movie', 'favorite_planet', 'stay_age', 'be_animal', 'live_in', 'fictional_pet', 'super_power'],
['Mr. P', '4/26', 'New Jersey', 'LCD Soundsystem', 'Brazil', 'The Truman Show', 'Venus', 28, 'Cat', 'Scadrial from Mistborn', 'War Horse from DnD', 'Slow Time'],
['Keitaro', '10/18', 'Pennsylvania', 'Motohiro Hata', 'Australia', 'Cars 1', 'Earth', 10, 'eagle', 'Hogwarts', 'dragon', 'Flight'],
['Penelope', '3/18', 'New York', 'Charli XCX', 'France', 'La La Land', 'Earth', 15, 'Manatee', 'Idk', 'Boltund', 'Flight'],
['Ayaan', '1/19', 'Virginia', 'Daniel Caesar', 'Tokyo', 'Into the Spider-Verse', 'Earth', 25, 'Hawk', 'Star Wars', 'The cat from Captain Marvel', 'Invisibility'],
['Ethan', '3/9', 'New York', 'Lil Yachty', 'Maldives', 'Shutter Island', 'Jupiter', 6, 'Dog', 'Bikini Bottom', 'Gary the Snail', 'Teleportation'],
['Jayden', '7/27', 'Florida', 'Kendrick Lamar', 'Dubai', 'War Dogs', 'Neptune', 21, 'Stingray', 'Hunger Games - Panem', 'Basilisk', 'Invisibility'],
['David', '11/17', 'China', 'Jay Chou', 'Mars', "don't have one", 'Earth', 22, 'pigeon', 'Swords and Magic', 'RedDragon', 'Unlimited life'],
['Daniel', '5/30', 'Canada', 'Old Kanye West', 'Japan', 'Interstellar', 'Saturn', 25, 'Cat', 'Pokemon', 'Phoenix', 'Time Travel'],
['Minhee', '11/24', 'South Korea', 'The Weeknd', 'Paris', 'Aladin', 'Earth', 10, 'Owl', 'Hogwarts', 'Jerry(mice)', 'Time Travel'],
['Christopher', '4/23', 'Taiwan', 'Mac Miller', 'Antarctica', 'Moneyball', 'Earth', 23, 'A pig', 'Star Wars', 'Ewok', 'Freeze time'],
['Claire', '6/5', 'New York', 'Ariana Grande', 'Japan', 'Lord of the Rings', 'Earth', 20, 'Dog', 'any peaceful world', 'narwhale', 'Flight'],
['Jiya', '8/23', 'New Jersey', 'My Chemical Romance', 'Paris', 'X-Men', 'Earth', 6, 'Butterfly', 'the Grishaverse', 'Unicorn', 'Invisibility'],
['Yujie', '3/25', 'China', 'EASon', 'Australia', 'Marvel', 'Earth', 18, 'whales', 'magic', 'cats', 'Invisibility'],
['Florence', '7/11', 'Indonesia', 'Bruno Mars', 'Italy', 'any mission impossible movies', 'Sun', 19, 'poodle dog', 'marvel', "moana's rooster", 'Teleportation '],
['Kevin', '12/9', 'China', 'Coldplay', 'The Maldives', 'Dune 2', 'Jupiter', 25, 'Orca', 'The matrix', 'The sand worm', 'Telepathy'],
['Tony', '10/17', 'China', 'Hatsune Miku', 'Andromeda', 'Interstellar', 'Saturn', 18, 'bird', 'Idk', 'Dragon', 'Time stop'],
['Deniz', '4/10', 'Turkey', 'Coldplay', 'Japan', 'Grown Ups', 'Jupiter', 24, 'Cat', 'StarWars', 'DrGON', 'Flight'],
]
data = [
['name', 'birthday', 'from', 'favorite_music', 'travel_dest', 'favorite_movie', 'favorite_planet', 'stay_age', 'be_animal', 'live_in', 'fictional_pet', 'super_power'],
['Mr. P', '4/26', 'New Jersey', 'LCD Soundsystem', 'Brazil', 'The Truman Show', 'Venus', 28, 'Cat', 'Scadrial from Mistborn', 'War Horse from DnD', 'Slow Time'],
['Keitaro', '10/18', 'Pennsylvania', 'Motohiro Hata', 'Australia', 'Cars 1', 'Earth', 10, 'eagle', 'Hogwarts', 'dragon', 'Flight'],
['Penelope', '3/18', 'New York', 'Charli XCX', 'France', 'La La Land', 'Earth', 15, 'Manatee', 'Idk', 'Boltund', 'Flight'],
['Ayaan', '1/19', 'Virginia', 'Daniel Caesar', 'Tokyo', 'Into the Spider-Verse', 'Earth', 25, 'Hawk', 'Star Wars', 'The cat from Captain Marvel', 'Invisibility'],
['Ethan', '3/9', 'New York', 'Lil Yachty', 'Maldives', 'Shutter Island', 'Jupiter', 6, 'Dog', 'Bikini Bottom', 'Gary the Snail', 'Teleportation'],
['Jayden', '7/27', 'Florida', 'Kendrick Lamar', 'Dubai', 'War Dogs', 'Neptune', 21, 'Stingray', 'Hunger Games - Panem', 'Basilisk', 'Invisibility'],
['David', '11/17', 'China', 'Jay Chou', 'Mars', "don't have one", 'Earth', 22, 'pigeon', 'Swords and Magic', 'RedDragon', 'Unlimited life'],
['Daniel', '5/30', 'Canada', 'Old Kanye West', 'Japan', 'Interstellar', 'Saturn', 25, 'Cat', 'Pokemon', 'Phoenix', 'Time Travel'],
['Minhee', '11/24', 'South Korea', 'The Weeknd', 'Paris', 'Aladin', 'Earth', 10, 'Owl', 'Hogwarts', 'Jerry(mice)', 'Time Travel'],
['Christopher', '4/23', 'Taiwan', 'Mac Miller', 'Antarctica', 'Moneyball', 'Earth', 23, 'A pig', 'Star Wars', 'Ewok', 'Freeze time'],
['Claire', '6/5', 'New York', 'Ariana Grande', 'Japan', 'Lord of the Rings', 'Earth', 20, 'Dog', 'any peaceful world', 'narwhale', 'Flight'],
['Jiya', '8/23', 'New Jersey', 'My Chemical Romance', 'Paris', 'X-Men', 'Earth', 6, 'Butterfly', 'the Grishaverse', 'Unicorn', 'Invisibility'],
['Yujie', '3/25', 'China', 'EASon', 'Australia', 'Marvel', 'Earth', 18, 'whales', 'magic', 'cats', 'Invisibility'],
['Florence', '7/11', 'Indonesia', 'Bruno Mars', 'Italy', 'any mission impossible movies', 'Sun', 19, 'poodle dog', 'marvel', "moana's rooster", 'Teleportation '],
['Kevin', '12/9', 'China', 'Coldplay', 'The Maldives', 'Dune 2', 'Jupiter', 25, 'Orca', 'The matrix', 'The sand worm', 'Telepathy'],
['Tony', '10/17', 'China', 'Hatsune Miku', 'Andromeda', 'Interstellar', 'Saturn', 18, 'bird', 'Idk', 'Dragon', 'Time stop'],
['Deniz', '4/10', 'Turkey', 'Coldplay', 'Japan', 'Grown Ups', 'Jupiter', 24, 'Cat', 'StarWars', 'DrGON', 'Flight'],
]
In [ ]:
Copied!
def find_idx_of_header(headers, header_name):
col_idx = 0
while col_idx < len(headers):
header = headers[col_idx]
if header == header_name:
break
col_idx += 1
return col_idx
headers = data[0]
from_col_idx = find_idx_of_header(headers, "from")
from_ny_count = 0
for row in data:
from_value = row[from_col_idx]
if from_value == "New York":
from_ny_count += 1
print(f"There are {from_ny_count} people from New York in our class")
def find_idx_of_header(headers, header_name):
col_idx = 0
while col_idx < len(headers):
header = headers[col_idx]
if header == header_name:
break
col_idx += 1
return col_idx
headers = data[0]
from_col_idx = find_idx_of_header(headers, "from")
from_ny_count = 0
for row in data:
from_value = row[from_col_idx]
if from_value == "New York":
from_ny_count += 1
print(f"There are {from_ny_count} people from New York in our class")
There are 3 people from New York in our class
In [ ]:
Copied!
travel_dest_idx = find_idx_of_header(headers, "travel_dest")
name_idx = find_idx_of_header(headers, "name")
for row_idx in range(len(data)):
travel_dest_value = data[row_idx][travel_dest_idx]
if travel_dest_value == "France" or travel_dest_value == "Paris":
name_value = data[row_idx][name_idx]
print(f"{name_value} wants to travel to {travel_dest_value}")
travel_dest_idx = find_idx_of_header(headers, "travel_dest")
name_idx = find_idx_of_header(headers, "name")
for row_idx in range(len(data)):
travel_dest_value = data[row_idx][travel_dest_idx]
if travel_dest_value == "France" or travel_dest_value == "Paris":
name_value = data[row_idx][name_idx]
print(f"{name_value} wants to travel to {travel_dest_value}")
Penelope wants to travel to France Minhee wants to travel to Paris Jiya wants to travel to Paris
In [ ]:
Copied!
stay_age_idx = find_idx_of_header(headers, "stay_age")
sum = 0
count = 0
data_without_header = data[1:]
for row in data_without_header:
stay_age = row[stay_age_idx]
sum += stay_age
count += 1
row_idx += 1
avg_stay_age = sum / count
print(f"The average age we want to stay is {avg_stay_age}")
stay_age_idx = find_idx_of_header(headers, "stay_age")
sum = 0
count = 0
data_without_header = data[1:]
for row in data_without_header:
stay_age = row[stay_age_idx]
sum += stay_age
count += 1
row_idx += 1
avg_stay_age = sum / count
print(f"The average age we want to stay is {avg_stay_age}")
The average age we want to stay is 18.529411764705884
In [ ]:
Copied!
def value_at(data, entry_name, col_name):
headers = data[0]
col_idx = headers.index(col_name)
name_col_idx = headers.index("name")
for row in data:
if row[name_col_idx] == entry_name:
return row[col_idx]
#value_at(data, "Mr. P", "favorite_music")
name = input("enter a name > ")
col = input("enter a column > ")
print(value_at(data, name, col))
def value_at(data, entry_name, col_name):
headers = data[0]
col_idx = headers.index(col_name)
name_col_idx = headers.index("name")
for row in data:
if row[name_col_idx] == entry_name:
return row[col_idx]
#value_at(data, "Mr. P", "favorite_music")
name = input("enter a name > ")
col = input("enter a column > ")
print(value_at(data, name, col))
enter a name > Mr. P enter a column > travel_dest Brazil
In [ ]:
Copied!
my_list = ['a', 'b', 'c', 'd', 'e']
my_list.index('c')
my_list = ['a', 'b', 'c', 'd', 'e']
my_list.index('c')
Out[ ]:
2
In [ ]:
Copied!
import pandas as pd
headers = data[0]
values = data[1:]
df = pd.DataFrame(values, columns=headers)
df["stay_age"].median()
import pandas as pd
headers = data[0]
values = data[1:]
df = pd.DataFrame(values, columns=headers)
df["stay_age"].median()
Out[ ]:
20.0
In [ ]:
Copied!