3. Writing Functions in Python¶
from datascience import *
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plots
plots.style.use('fivethirtyeight')
Let’s start out by creating a table of integers and their cubes. Then we can see how the .apply
method works.
ints = np.arange(1,21)
ints
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20])
cubes = ints ** 3
cubes
array([ 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000, 1331,
1728, 2197, 2744, 3375, 4096, 4913, 5832, 6859, 8000], dtype=int32)
digits = Table().with_columns('Integers', ints,
'Cubes', cubes)
digits
Integers | Cubes |
---|---|
1 | 1 |
2 | 8 |
3 | 27 |
4 | 64 |
5 | 125 |
6 | 216 |
7 | 343 |
8 | 512 |
9 | 729 |
10 | 1000 |
... (10 rows omitted)
def cube_root(x):
return x ** (1/3)
cube_root(8)
2.0
cube_root(1000)
9.999999999999998
digits.apply(cube_root,'Cubes')
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13.,
14., 15., 16., 17., 18., 19., 20.])
This can also be accomplished with the .column
method.
cube_root(digits.column('Cubes'))
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13.,
14., 15., 16., 17., 18., 19., 20.])