+
between two strings concatenates the strings.*
between a string and an integer repeats the string.'back'+'pack'
'backpack'
'bye'*3
'byebyebye'
fave_string = 'My favorite class is DSC 10!'
fave_string.title()
'My Favorite Class Is Dsc 10!'
fave_string.upper()
'MY FAVORITE CLASS IS DSC 10!'
fave_string.replace('favorite', '😍' * 3)
'My 😍😍😍 class is DSC 10!'
# You can use string methods directly on strings, even if not stored in a variable.
"hello".upper()
'HELLO'
# len is not a method, since it doesn't use dot notation.
len(fave_string)
28
str
.int
and float
.str(3)
'3'
float('3')
3.0
int('4')
4
int('baby panda')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) /tmp/ipykernel_323/455936715.py in <module> ----> 1 int('baby panda') ValueError: invalid literal for int() with base 10: 'baby panda'
int('4.3')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) /tmp/ipykernel_323/756068685.py in <module> ----> 1 int('4.3') ValueError: invalid literal for int() with base 10: '4.3'
Assume you have run the following statements:
x = 3
y = '4'
z = '5.6'
Choose the expression that will be evaluated without an error.
A. x + y
B. x + int(y + z)
C. str(x) + int(y)
D. str(x) + z
E. All of them have errors
int
s or float
s) and pieces of text (as strings). But we often we'll work with sequences, or ordered collections, of several data values.The mean is a one-number summary of a collection of numbers.
For example, the mean of $1$, $4$, $7$, and $12$ is $\frac{1 + 4 + 7 + 12}{4} = 6$.
Observe that the mean:
Like the mean, the median is a one-number summary of a collection of numbers.
Find two different datasets that have the same mean and different medians.
Find two different datasets that have the same median and different means.
Find two different datasets that have the same median and the same mean.
Means and medians are just summaries; they don't tell the whole story about a dataset!
In a few weeks, we'll learn about how to visualize the distribution of a collection of numbers using a histogram.
These two distributions have different means but the same median!
How would we store the temperatures for a week to compute the average temperature?
Our best solution right now is to create a separate variable for each day of the week.
temp_sunday = 68
temp_monday = 73
temp_tuesday = 70
temp_wednesday = 74
temp_thursday = 76
temp_friday = 72
temp_saturday = 74
This technically allows us to do things like compute the average temperature:
avg_temperature = 1/7 * (
temp_sunday
+ temp_monday
+ temp_tuesday
+ ...)
Imagine a whole month's data, or a whole year's data. It seems like we need a better solution.
In Python, a list is used to store multiple values within a single variable. To create a new list from scratch, we use [
square brackets]
.
temperature_list = [68, 73, 70, 74, 76, 72, 74]
len(temperature_list)
7
Notice that the elements in a list don't need to be unique!
To find the average temperature, we just need to divide the sum of the temperatures by the number of temperatures recorded:
temperature_list
[68, 73, 70, 74, 76, 72, 74]
sum(temperature_list) / len(temperature_list)
72.42857142857143
The type
of a list is... list
.
temperature_list
[68, 73, 70, 74, 76, 72, 74]
type(temperature_list)
list
Within a list, you can store elements of different types.
mixed_list = [-2, 2.5, 'ucsd', [1, 3]]
mixed_list
[-2, 2.5, 'ucsd', [1, 3]]
NumPy (pronounced "num pie") is a Python library (module) that provides support for arrays and operations on them.
The babypandas
library, which you will learn about soon, goes hand-in-hand with NumPy.
To use numpy
, we need to import it. It's usually imported as np
(but doesn't have to be!)
import numpy as np
Think of NumPy arrays (just "arrays" from now on) as fancy, faster lists.
To create an array, we pass a list as input to the np.array
function.
np.array([4, 9, 1, 2])
array([4, 9, 1, 2])
temperature_array = np.array([68, 73, 70, 74, 76, 72, 74])
temperature_array
array([68, 73, 70, 74, 76, 72, 74])
temperature_list
[68, 73, 70, 74, 76, 72, 74]
# No square brackets, because temperature_list is already a list!
np.array(temperature_list)
array([68, 73, 70, 74, 76, 72, 74])
When people wait in line, each person has a position.
Similarly, each element of an array (and list) has a position.
arr_name
at position pos
, we use the syntax arr_name[pos]
.temperature_array
array([68, 73, 70, 74, 76, 72, 74])
# If a position is negative, count from the end!
temperature_array[-2]
72
Earlier in the lecture, we saw that lists can store elements of multiple types.
nums_and_strings_lst = ['uc', 'sd', 1961, 3.14]
nums_and_strings_lst
['uc', 'sd', 1961, 3.14]
This is not true of arrays – all elements in an array must be of the same type.
# All elements are converted to strings!
np.array(nums_and_strings_lst)
array(['uc', 'sd', '1961', '3.14'], dtype='<U32')
Arrays make it easy to perform the same operation to every element. This behavior is formally known as "broadcasting".
temperature_array
array([68, 73, 70, 74, 76, 72, 74])
# Increase all temperatures by 3 degrees.
temperature_array + 3
array([71, 76, 73, 77, 79, 75, 77])
# Halve all temperatures.
temperature_array / 2
array([34. , 36.5, 35. , 37. , 38. , 36. , 37. ])
# Convert all temperatures to Celsius.
(5 / 9) * (temperature_array - 32)
array([20. , 22.77777778, 21.11111111, 23.33333333, 24.44444444, 22.22222222, 23.33333333])
Note: In none of the above cells did we actually modify temperature_array
! Each of those expressions created a new array.
temperature_array
array([68, 73, 70, 74, 76, 72, 74])
To actually change temperature_array
, we need to reassign it to a new array.
temperature_array = (5 / 9) * (temperature_array - 32)
# Now in Celsius!
temperature_array
array([20. , 22.77777778, 21.11111111, 23.33333333, 24.44444444, 22.22222222, 23.33333333])
a = np.array([4, 5, -1])
b = np.array([2, 3, 2])
a + b
array([6, 8, 1])
a / b
array([ 2. , 1.66666667, -0.5 ])
a ** 2 + b ** 2
array([20, 34, 5])
Arrays work with a variety of methods, which are functions designed to operate specifically on arrays.
Call these methods using dot notation, e.g. array_name.method()
.
temperature_array.max()
24.444444444444446
temperature_array.mean()
22.460317460317462
We often find ourselves needing to make arrays like this:
day_of_month = np.array([
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31
])
There needs to be an easier way to do this!
np.arange
.np.arange(start, end, step)
. This returns an array such that:start
. By default, start
is 0.step
, until (but excluding) end
. By default, step
is 1.# Start at 0, end before 8, step by 1.
# This will be our most common use-case!
np.arange(8)
array([0, 1, 2, 3, 4, 5, 6, 7])
# Start at 5, end before 10, step by 1.
np.arange(5, 10)
array([5, 6, 7, 8, 9])
# Start at 3, end before 32, step by 5.
np.arange(3, 32, 5)
array([ 3, 8, 13, 18, 23, 28])
The step size in np.arange
can be fractional, or even negative. Predict what arrays will be produced by each line of code below. Then copy each line into a code cell and run it to see if you're right.
np.arange(-3, 2, 0.5)
np.arange(1, -10, -3)
...
...
🎉 Congrats! 🎉 You won the lottery 💰. Here's how your payout works: on the first day of September, you are paid \$0.01. Every day thereafter, your pay doubles, so on the second day you're paid \$0.02, on the third day you're paid \$0.04, on the fourth day you're paid \$0.08, and so on.
September has 30 days.
Write a one-line expression that uses the numbers 2
and 30
, along with the function np.arange
and the method .sum()
, that computes the total amount in dollars you will be paid in September.
...
After trying the challenge problem on your own, watch this walkthrough 🎥 video.
np.arange
.We'll see how to use Python to work with real-world tabular data (data you might otherwise work with in a spreadsheet). This is where it gets fun!