Skip to content
Marcel Stampfer edited this page Nov 2, 2015 · 16 revisions

Elementary arithmetic operations

import numpy as np
import scipy.io
import scipy.misc
import matplotlib.pyplot as plt
5+6
11
3-2
1
5*8
40
1/2
0
1./2 # Explain this
0.5
2**6
64

Logical operations

1 != 2 # True
True
1 and 0 # False
0
1 or 0 # True
1
1 != 0 # XOR
True
a='foo'
b='bar'
bool(a) != bool(b)
False
b=None
bool(a) != bool(b) # Explain this
True

####Python variables and types ####Displaying variables

b=3
b
3
from math import pi
b=pi
b
3.141592653589793
float('%1.4f'%b)
3.1416
float('{:1.5}'.format(b))
3.1416

##Numpy basics : Vectors and matrices

import numpy as np
a=np.array([[1,2],[3,4],[5,6]])
a
array([[1, 2],
       [3, 4],
       [5, 6]])
v=[1,2,3]   # list
v
[1, 2, 3]
v=np.array([1,2,3]) # numpy array
v
array([1, 2, 3])
v=np.arange(1,2,0.1)
v
array([ 1. ,  1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8,  1.9])
v.tolist()
[1.0,
 1.1,
 1.2000000000000002,
 1.3000000000000003,
 1.4000000000000004,
 1.5000000000000004,
 1.6000000000000005,
 1.7000000000000006,
 1.8000000000000007,
 1.9000000000000008]
v=range(1,6)
v
[1, 2, 3, 4, 5]
v=np.linspace(1,2,11)
v
array([ 1. ,  1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8,  1.9,  2. ])
###Comprehensions
####list comprehension
v=[1,2,3]
[e**2 for e in v]
[1, 4, 9]
[e**2 for e in v if e%2 !=0]
[1, 9]
[e**2 if e%2 != 0 else -1 for e in v]
[1, -1, 9]

####dictionary comprehension

d = {'a':1, 'b':2, 'c':3}   
{v: k for k, v in d.items()}   # swap keys and values
{1: 'a', 2: 'b', 3: 'c'}
{1: 'a', 2: 'b', 3: 'c'}

####set comprehension

{x**2 for x in [1, 1, 2]}
set([1, 4])
{1, 4}

###Special matrix functions

ones=np.ones((3,2))
ones
array([[ 1.,  1.],
       [ 1.,  1.],
       [ 1.,  1.]])
3*ones
array([[ 3.,  3.],
       [ 3.,  3.],
       [ 3.,  3.]])
np.zeros((3,2))
array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]])
np.random.rand(3,2)
array([[ 0.62274829,  0.09702351],
       [ 0.63787983,  0.7836852 ],
       [ 0.2725037 ,  0.05886131]])
np.random.randn(3,2)
array([[ 0.91457171, -2.09292019],
       [-0.66121188,  1.47599627],
       [ 0.5300655 , -0.7618794 ]])

id=np.eye(3) id

3*id
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-109-0412ab2e6bd6> in <module>()
----> 1 3*id


TypeError: unsupported operand type(s) for *: 'int' and 'builtin_function_or_method'

##Moving data around ###shape/size of a matrix

a=np.random.rand(3,2)
a.shape
(3, 2)
a.size
6
###Loading files in python
file=open('../ex6/emailSample1.txt', 'r')
file_contents=file.read()
file_contents
"> Anyone knows how much it costs to host a web portal ?\n>\nWell, it depends on how many visitors you're expecting.\nThis can be anywhere from less than 10 bucks a month to a couple of $100. \nYou should checkout http://www.rackspace.com/ or perhaps Amazon EC2 \nif youre running something big..\n\nTo unsubscribe yourself from this mailing list, send an email to:\[email protected]\n\n"
%pylab inline
data = scipy.misc.imread('../ex7/bird_small.png')
plt.imshow(data)
Populating the interactive namespace from numpy and matplotlib


WARNING: pylab import has clobbered these variables: ['mat', 'rand', 'ones', 'pi', 'e']
`%matplotlib` prevents importing * from pylab and numpy





<matplotlib.image.AxesImage at 0x10dc711d0>

png

data = np.loadtxt('ex1data1.txt', delimiter=',')
data
array([[  6.1101 ,  17.592  ],
       [  5.5277 ,   9.1302 ],
       [  8.5186 ,  13.662  ],
       [  7.0032 ,  11.854  ],
       [  5.8598 ,   6.8233 ],
       [  8.3829 ,  11.886  ],
       [  7.4764 ,   4.3483 ],
       [  8.5781 ,  12.     ],
       [  6.4862 ,   6.5987 ],
       [  5.0546 ,   3.8166 ],
       [  5.7107 ,   3.2522 ],
       [ 14.164  ,  15.505  ],
       [  5.734  ,   3.1551 ],
       [  8.4084 ,   7.2258 ],
       [  5.6407 ,   0.71618],
       [  5.3794 ,   3.5129 ],
       [  6.3654 ,   5.3048 ],
       [  5.1301 ,   0.56077],
       [  6.4296 ,   3.6518 ],
       [  7.0708 ,   5.3893 ],
       [  6.1891 ,   3.1386 ],
       [ 20.27   ,  21.767  ],
       [  5.4901 ,   4.263  ],
       [  6.3261 ,   5.1875 ],
       [  5.5649 ,   3.0825 ],
       [ 18.945  ,  22.638  ],
       [ 12.828  ,  13.501  ],
       [ 10.957  ,   7.0467 ],
       [ 13.176  ,  14.692  ],
       [ 22.203  ,  24.147  ],
       [  5.2524 ,  -1.22   ],
       [  6.5894 ,   5.9966 ],
       [  9.2482 ,  12.134  ],
       [  5.8918 ,   1.8495 ],
       [  8.2111 ,   6.5426 ],
       [  7.9334 ,   4.5623 ],
       [  8.0959 ,   4.1164 ],
       [  5.6063 ,   3.3928 ],
       [ 12.836  ,  10.117  ],
       [  6.3534 ,   5.4974 ],
       [  5.4069 ,   0.55657],
       [  6.8825 ,   3.9115 ],
       [ 11.708  ,   5.3854 ],
       [  5.7737 ,   2.4406 ],
       [  7.8247 ,   6.7318 ],
       [  7.0931 ,   1.0463 ],
       [  5.0702 ,   5.1337 ],
       [  5.8014 ,   1.844  ],
       [ 11.7    ,   8.0043 ],
       [  5.5416 ,   1.0179 ],
       [  7.5402 ,   6.7504 ],
       [  5.3077 ,   1.8396 ],
       [  7.4239 ,   4.2885 ],
       [  7.6031 ,   4.9981 ],
       [  6.3328 ,   1.4233 ],
       [  6.3589 ,  -1.4211 ],
       [  6.2742 ,   2.4756 ],
       [  5.6397 ,   4.6042 ],
       [  9.3102 ,   3.9624 ],
       [  9.4536 ,   5.4141 ],
       [  8.8254 ,   5.1694 ],
       [  5.1793 ,  -0.74279],
       [ 21.279  ,  17.929  ],
       [ 14.908  ,  12.054  ],
       [ 18.959  ,  17.054  ],
       [  7.2182 ,   4.8852 ],
       [  8.2951 ,   5.7442 ],
       [ 10.236  ,   7.7754 ],
       [  5.4994 ,   1.0173 ],
       [ 20.341  ,  20.992  ],
       [ 10.136  ,   6.6799 ],
       [  7.3345 ,   4.0259 ],
       [  6.0062 ,   1.2784 ],
       [  7.2259 ,   3.3411 ],
       [  5.0269 ,  -2.6807 ],
       [  6.5479 ,   0.29678],
       [  7.5386 ,   3.8845 ],
       [  5.0365 ,   5.7014 ],
       [ 10.274  ,   6.7526 ],
       [  5.1077 ,   2.0576 ],
       [  5.7292 ,   0.47953],
       [  5.1884 ,   0.20421],
       [  6.3557 ,   0.67861],
       [  9.7687 ,   7.5435 ],
       [  6.5159 ,   5.3436 ],
       [  8.5172 ,   4.2415 ],
       [  9.1802 ,   6.7981 ],
       [  6.002  ,   0.92695],
       [  5.5204 ,   0.152  ],
       [  5.0594 ,   2.8214 ],
       [  5.7077 ,   1.8451 ],
       [  7.6366 ,   4.2959 ],
       [  5.8707 ,   7.2029 ],
       [  5.3054 ,   1.9869 ],
       [  8.2934 ,   0.14454],
       [ 13.394  ,   9.0551 ],
       [  5.4369 ,   0.61705]])
data = scipy.io.loadmat('ex3data1.mat')
data
---------------------------------------------------------------------------

IOError                                   Traceback (most recent call last)

<ipython-input-116-f2dd930e4dd8> in <module>()
----> 1 data = scipy.io.loadmat('ex3data1.mat')
      2 data


/Users/marcel/.virtualenvs/2.7.6/lib/python2.7/site-packages/scipy/io/matlab/mio.pyc in loadmat(file_name, mdict, appendmat, **kwargs)
    132     """
    133     variable_names = kwargs.pop('variable_names', None)
--> 134     MR = mat_reader_factory(file_name, appendmat, **kwargs)
    135     matfile_dict = MR.get_variables(variable_names)
    136     if mdict is not None:


/Users/marcel/.virtualenvs/2.7.6/lib/python2.7/site-packages/scipy/io/matlab/mio.pyc in mat_reader_factory(file_name, appendmat, **kwargs)
     55        type detected in `filename`.
     56     """
---> 57     byte_stream = _open_file(file_name, appendmat)
     58     mjv, mnv = get_matfile_version(byte_stream)
     59     if mjv == 0:


/Users/marcel/.virtualenvs/2.7.6/lib/python2.7/site-packages/scipy/io/matlab/mio.pyc in _open_file(file_like, appendmat)
     21     if isinstance(file_like, string_types):
     22         try:
---> 23             return open(file_like, 'rb')
     24         except IOError as e:
     25             if appendmat and not file_like.endswith('.mat'):


IOError: [Errno 2] No such file or directory: 'ex3data1.mat'

##Manipulating matrices ###Indexing and Slicing

x = np.arange(10)
x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
x[:]
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
x[1:]
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
x[:5]
array([0, 1, 2, 3, 4])
x[2]
2
x[-2]
8
x=x.reshape((2,5))
x
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
x[1,3]
8
x[0]
array([0, 1, 2, 3, 4])
x = np.arange(10)
x[2:5]
array([2, 3, 4])
x[1:7:2]
array([1, 3, 5])
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
arr2d
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
arr2d[2]
array([7, 8, 9])
arr2d[0][1]
2
arr2d[0,1]
2

###Boolean indexing

mat = np.array(['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']).reshape((3,3))
mat
array([['The', 'quick', 'brown'],
       ['fox', 'jumped', 'over'],
       ['the', 'lazy', 'dog']], 
      dtype='|S6')
rand = np.random.randn(3,3)>0
rand
array([[False, False,  True],
       [ True,  True,  True],
       [ True, False, False]], dtype=bool)
mat[rand]
array(['brown', 'fox', 'jumped', 'over', 'the'], 
      dtype='|S6')

###Flattening

arr = np.arange(9).reshape((3,3))
arr
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
arr.flatten()
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
arr.ravel()
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
arr.flatten(1)
array([0, 3, 6, 1, 4, 7, 2, 5, 8])

###Vector assignments

arr = np.arange(10)
arr
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
arr[4:8]=10
arr
array([ 0,  1,  2,  3, 10, 10, 10, 10,  8,  9])
slice=arr[4:8]
slice
array([10, 10, 10, 10])
slice[:]=-5
slice
array([-5, -5, -5, -5])
slice[1]=50
slice
array([-5, 50, -5, -5])
arr_copy=arr.copy()
arr_copy
array([ 0,  1,  2,  3, -5, 50, -5, -5,  8,  9])
arr_copy[4:8]=20
arr_copy
array([ 0,  1,  2,  3, 20, 20, 20, 20,  8,  9])
arr
array([ 0,  1,  2,  3, -5, 50, -5, -5,  8,  9])

Concatenating

mat = np.array(['The', 'quick', 'brown', 'fox'])
mat2 = np.array(['jumped', 'over', 'the', 'lazy'])
 np.hstack((mat,mat2))
array(['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy'], 
      dtype='|S6')
 np.vstack((mat,mat2))
array([['The', 'quick', 'brown', 'fox'],
       ['jumped', 'over', 'the', 'lazy']], 
      dtype='|S6')
 np.column_stack((mat,mat2))
array([['The', 'jumped'],
       ['quick', 'over'],
       ['brown', 'the'],
       ['fox', 'lazy']], 
      dtype='|S6')
arr = np.arange(12).reshape((3, 4))
arr
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
np.concatenate((arr,arr), axis=1)
array([[ 0,  1,  2,  3,  0,  1,  2,  3],
       [ 4,  5,  6,  7,  4,  5,  6,  7],
       [ 8,  9, 10, 11,  8,  9, 10, 11]])
np.concatenate((arr,arr), axis=0)
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
arr = np.arange(5)
np.concatenate((arr,arr), axis=0)
array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4])

###Matrix multiplication

x=np.array([[1,2,3], [4,5,6], [7,8,9]])
y=np.array([[1,2,3], [4,5,6], [7,8,9]])
np.dot(x,y)
array([[ 30,  36,  42],
       [ 66,  81,  96],
       [102, 126, 150]])
x.dot(y)
array([[ 30,  36,  42],
       [ 66,  81,  96],
       [102, 126, 150]])
# Element-wise multiplication
x*y
array([[ 1,  4,  9],
       [16, 25, 36],
       [49, 64, 81]])

####Element-wise squaring

x**2
array([[ 1,  4,  9],
       [16, 25, 36],
       [49, 64, 81]])

####Element-wise reciprical

1./x
array([[ 1.        ,  0.5       ,  0.33333333],
       [ 0.25      ,  0.2       ,  0.16666667],
       [ 0.14285714,  0.125     ,  0.11111111]])

####Element-wise logarithms/exponents

np.log(x)
array([[ 0.        ,  0.69314718,  1.09861229],
       [ 1.38629436,  1.60943791,  1.79175947],
       [ 1.94591015,  2.07944154,  2.19722458]])
np.exp(x)
array([[  2.71828183e+00,   7.38905610e+00,   2.00855369e+01],
       [  5.45981500e+01,   1.48413159e+02,   4.03428793e+02],
       [  1.09663316e+03,   2.98095799e+03,   8.10308393e+03]])

####Element-wise addition

1+x
array([[ 2,  3,  4],
       [ 5,  6,  7],
       [ 8,  9, 10]])

###Transpose of a matrix

x.T
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])

###Maximum and minimum of matrix values

np.max(x)
9
np.min(x)
1
###sum and product of all elements
np.sum(x)
45
np.sum(x,axis=0)
array([12, 15, 18])
np.sum(x,axis=1)
array([ 6, 15, 24])
np.sum(x)
45
np.product(x)
362880
np.product(x,axis=0)
array([ 28,  80, 162])
np.product(x,axis=1)
array([  6, 120, 504])

###Inverse and pseudo-inverse of a matrix

x=2*np.eye(3)
np.linalg.inv(x)
array([[ 0.5,  0. ,  0. ],
       [ 0. ,  0.5,  0. ],
       [ 0. ,  0. ,  0.5]])
np.linalg.pinv(x)
array([[ 0.5,  0. ,  0. ],
       [ 0. ,  0.5,  0. ],
       [ 0. ,  0. ,  0.5]])

##Plotting data ###Plotting generated data

plt.plot(np.arange(10))
[<matplotlib.lines.Line2D at 0x10dd05f50>]

png

##Line color, labels, title and legend ###Saving a graph ###Subplots ###Axis scaling ###Creating/clearing figures ##Control statements ###For loops

li = ['a', 'b', 'e']
for e in li:
    print e
a
b
e
d = enumerate(li)
for k,v in d:
    print k,v
0 a
1 b
2 e

###While loops

n = ''
while n.strip() != 'hello':
    n = raw_input("Please enter 'hello':")
Please enter 'hello':goodbye
Please enter 'hello':hello

###break statement

while True:
    n = raw_input("Please enter 'hello':")
    if n.strip() == 'hello':
        break
Please enter 'hello':bye
Please enter 'hello':hello

###if-elif-else statement

x = int(raw_input("Please enter an integer: "))

if x < 0:
    x = 0
    print 'Negative changed to zero'
elif x == 0:
    print 'Zero'
elif x == 1:
    print 'Single'
else:
    print 'More'
Please enter an integer: 42
More

##Functions

###PYTHONPATH environment variable ##Vectorization ###Vectorized implementation ###Unvectorized implementation

Clone this wiki locally