names = ['bill', 'sarah', 'cal', 'nina', 'joe']
names[1]
me = ['berkeley', 22, 1998, '🇨🇦']
[1, 2, 3] + [4, 5, 6]
numbers = [5, 4, 9, 12, 18]
new_numbers = []
for num in numbers:
new_numbers.append(num + 5)
new_numbers
# Necessary to use numpy arrays!
import numpy as np
# Array with 4 numbers
np.array([4, 9, 1, 2])
# Array with 3 strings
np.array(['how', 'are', 'you'])
# Empty array
np.array([])
numbers = [5, 4, 9, 12, 18]
numbers
type(numbers)
numbers_arr = np.array(numbers)
numbers_arr
type(numbers_arr)
numbers_arr
numbers_arr * 2
numbers_arr - 5
numbers_arr // 2
numbers_arr ** 2 - 1
c_temps = [17, 18, 22, -4.5, 15, 9, 0, 3, 8]
# Using vanilla lists:
f_temps = []
for c in c_temps:
f = (9 / 5) * c + 32
f_temps.append(f)
f_temps
# Using arrays: no for loop!
(9 / 5) * np.array(c_temps) + 32
numbers_arr
np.sqrt(numbers_arr)
np.log(numbers_arr)
np.sin(numbers_arr)
np.sqrt(144)
my_tips = [0.15, 0.16, 0.22, 0.39]
your_tips = [0.25, 0.19, 0.08]
tips = np.array(my_tips + your_tips)
tips_pct = 100 * tips
a = np.array([1, 2, 3])
b = np.array([-4, 5, 9])
a + b
a - 2 * b
a**2 + b**2
# a and c have different lengths, so you can't add them element-wise
c = np.array([9, 0, 2, 4])
a + c
pop_2019 = np.array([100, 55, 23, 91, 121])
pop_2020 = np.array([101, 45, 23, 93, 118])
# Change from 2020 to 2019
pop_2020 - pop_2019
# Percent change
100 * (pop_2020 - pop_2019) / pop_2019
# a = np.array([3, 4, 5])
# b = np.array([7, -4.0, 5])
# c = (a + b) / (a - b)
pop_2020 = np.array([101, 45, 23, 93, 118])
pop_2020[0]
pop_2020[-2]
pop_2020.item(0)
pop_2020.item(-2)
pop_2020
# Sum of all elements
# Equivalent to np.sum(pop_2020)
pop_2020.sum()
# Average of all elements
# Equivalent to np.mean(pop_2020)
pop_2020.mean()
# Product of all elements
# Equivalent to np.prod(pop_2020)
pop_2020.prod()
np.arange(10)
np.arange(3, 13, 3)
# Powers of 2
2**np.arange(10)
# 1^2 + 2^2 + 3^2 + ... + 99^2 + 100^2
np.sum(np.arange(101)**2)
# 2. means 2.0
some_values = [2, 3, 3.5, 4, False]
np.array(some_values)
np.array(some_values).item(0)
other_values = [9, 8, 'hello', -14.5]
np.array(other_values)
pop_2020
# Cumulative sum: for each element,
# add all elements so far
np.cumsum(pop_2020)
# Difference: takes the differences
# of consecutive differences
np.diff(pop_2020)
# count_nonzero: counts the number of elements
# that are not equal to 0
np.count_nonzero(np.array([1, 2, 3, 0, 0, 4, -5]))