Numpy

Create Arrays

From list:

mylist = [1, 2, 3]
x = np.array(mylist)

or:

x = np.array([1, 2, 3])

List of lists = multidimensional array:

m = np.array([[7, 8, 9], [10, 11, 12]])

shape: gives dimensions of array in rows & columns:

m = array([[ 7,  8,  9],
           [10, 11, 12]])
m.shape
(2, 3)

arange: set of values within an interval:

n = np.arange(0, 30, 2) # start at 0 count up by 2, stop before 30

array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28])

s = np.arange(13)**2 # zero to 13, each raised to power of 2

array([  0,   1,   4,   9,  16,  25,  36,  49,  64,  81, 100, 121, 144])

reshape: same data, new shape

n = n.reshape(3, 5) # reshape array to be 3x5
array([[ 0,  2,  4,  6,  8],
       [10, 12, 14, 16, 18],
       [20, 22, 24, 26, 28]])

linspace: evenly spaced numbers over a given interval

o = np.linspace(0, 4, 9) # return 9 evenly spaced values from 0 to 4

ones: create array of given shape, with 1’s

zeros: create array of given shape, with zeros

>>> my_array = np.zeros((5,5))
>>> my_array
array([[0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.]])

eye: 2d array with ones diagonal and zeros elsewhere

>>> np.eye(3)
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

diag: extracts a diagonal or constructs diagonal array

y = np.array([4, 5, 6])
np.diag(y)
array([[4, 0, 0],
       [0, 5, 0],
       [0, 0, 6]])

Repeating List

np.array([1, 2, 3] * 3)
array([1, 2, 3, 1, 2, 3, 1, 2, 3])

Combine Arrays

Note that ‘int’ makes the 1’s integers instead of “1.”

p = np.ones([2, 3], int)

array([[1, 1, 1],
       [1, 1, 1]])

Stack arrays in sequence vertically (row wise):

np.vstack([p, 2*p])
array([[1, 1, 1],
       [1, 1, 1],
       [2, 2, 2],
       [2, 2, 2]])

Note ``2 * p`` multiplies all the elements in y by 2.

Stack arrays in sequence horizontally (colum wise):

np.hstack([p, 2*p])
array([[1, 1, 1, 2, 2, 2],
       [1, 1, 1, 2, 2, 2]])

Operations

Element wise operations:

print(x + y) # elementwise addition     [1 2 3] + [4 5 6] = [5  7  9]
print(x - y) # elementwise subtraction  [1 2 3] - [4 5 6] = [-3 -3 -3]

print(x * y) # elementwise multiplication  [1 2 3] * [4 5 6] = [4  10  18]
print(x / y) # elementwise divison         [1 2 3] / [4 5 6] = [0.25  0.4  0.5]

Dot Product

x = array([1, 2, 3])
y = array([4, 5, 6])

x.dot(y) = 1*4 + 2*5 + 3*6
32

Transpose an array:

z = array([[ 4,  5,  6],
           [16, 25, 36]])

z.T  # T = transpose
array([[ 4, 16],
       [ 5, 25],
       [ 6, 36]])

See data type of array elements:

z.dtype
dtype('int64')

Cast to a specified type:

z = z.astype('f')  # cast to float
z.dtype
dtype('float32')

Math Functions

a = np.array([-4, -2, 1, 3, 5])

a.sum()
3

a.max()
5

a.min()
-4

a.mean()
0.6

a.std()
3.2619012860600183

Get index of minimum and maximum values:

a.argmax()
4

a.argmin()
0

Indexing and Slicing

Get value at specific index

s = array([  0,   1,   4,   9,  16,  25,  36,  49,  64,  81, 100, 121, 144])

s[0], s[4], s[-1]
(0, 16, 144)

Range of values:

s[1:5]
array([ 1,  4,  9, 16])

Get last four values:

s[-4:]
array([ 81, 100, 121, 144])

Get step size: array[start:stop:stepsize] Starting with 5th element from the end (64), count backwards by 2 until beginning of array reached:

s[-5::-2]
array([64, 36, 16,  4,  0])

Slice a multidimensional array:

r = array([[ 0,  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, 32, 33, 34, 35]])
r[2, 2]
14

r[3, 3:6]  # get elements 3 to 5 in row 3
array([21, 22, 23])

Get all rows up to and not including row 2, then all columns up to and not including the last:

r[:2, :-1]
array([[ 0,  1,  2,  3,  4],
       [ 6,  7,  8,  9, 10]])

Last row, every other element:

r[-1, ::2]
array([30, 32, 34])

Get values from array that are greater than 30:

r[r > 30]
array([31, 32, 33, 34, 35])

Change values greater than 30 to 30:

r[r > 30] = 30
array([[ 0,  0,  0,  3,  4,  5],
       [ 0,  0,  0,  9, 10, 11],
       [ 0,  0,  0, 15, 16, 17],
       [18, 19, 20, 21, 22, 23],
       [24, 25, 26, 27, 28, 29],
       [30, 30, 30, 30, 30, 30]])

Copying Data

CAUTION..modifying a slice of an array changes the original array!

r = array([[ 0,  1,  2,  3,  4,  5],
           [ 6,  7,  8,  9, 10, 11],
           [12, 13, 14, 15, 16, 17],
           [12, 13, 14, 15, 16, 17],
           [18, 19, 20, 21, 22, 23],
           [24, 25, 26, 27, 28, 29],
           [30, 31, 32, 33, 34, 35]])

r2 is a slice of r:

r2 = r[:3,:3]
r2
array([[ 0,  1,  2],
       [ 6,  7,  8],
       [12, 13, 14]])

Set all values in r2 to 0:

r2[:] = 0
r2
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])

Original array ‘r’ has also been changed!

r
array([[ 0,  0,  0,  3,  4,  5],
       [ 0,  0,  0,  9, 10, 11],
       [ 0,  0,  0, 15, 16, 17],
       [18, 19, 20, 21, 22, 23],
       [24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35]])

Make a copy of an array that will NOT affect the original:

r_copy = c.copy()

Iterating Over Arrays

Create an array of random numbers from 0 to 9:

test = np.random.randint(0, 10, (4,3))

array([[4, 2, 9],
       [6, 9, 6],
       [4, 7, 7],
       [2, 6, 3]]

Iterate by row:

for row in test:
    print(row)

[4 2 9]
[6 9 6]
[4 7 7]
[2 6 3]

Iterate by index:

for i in range(len(test)):
    print(test[i])

[4 2 9]
[6 9 6]
[4 7 7]
[2 6 3]

Iterate by row and index:

for i, row in enumerate(test):
    print('row', i, 'is', row)

row 0 is [4 2 9]
row 1 is [6 9 6]
row 2 is [4 7 7]
row 3 is [2 6 3]

Iterate over multiple iterables:

test = array([[4, 2, 9],
              [6, 9, 6],
              [4, 7, 7],
              [2, 6, 3]]

test2 = array([[16,  4, 81],
               [36, 81, 36],
               [16, 49, 49],
               [ 4, 36,  9]])

for i, j in zip(test, test2):
    print(i,'+',j,'=',i+j)

[4 2 9] + [16  4 81] = [20  6 90]
[6 9 6] + [36 81 36] = [42 90 42]
[4 7 7] + [16 49 49] = [20 56 56]
[2 6 3] + [ 4 36  9] = [ 6 42 12]