In [1]:
import numpy as np
1. Array Creation¶
In [2]:
alist = [1,2,3]
arr = np.array(alist) # converting list to ndarray
arr
Out[2]:
In [3]:
arr.tolist() # Converting ndarray to list
Out[3]:
In [4]:
np.zeros(5) # Creating an array of zeros with five elements
Out[4]:
In [5]:
np.arange(10) # Create an ndarray with 10 elements from 0 to 9
Out[5]:
In [6]:
np.arange(3,8) # from to
Out[6]:
In [7]:
np.linspace(0, 5, 9) # from to steps
Out[7]:
In [8]:
np.logspace(0, 5, 10, base=10.0)
Out[8]:
In [9]:
np.zeros((5,5)) # Creating a 5x5 array of zeros
Out[9]:
In [10]:
np.ones((3,3)) # Creating a 5x5 array of ones
Out[10]:
In [11]:
arr1d = np.arange(12)
arr2d = arr1d.reshape((3,4))
arr2d
Out[11]:
In [12]:
arr2d = np.reshape(arr1d,(4,3))
arr2d
Out[12]:
2. Indexing and Slicing¶
In [13]:
alist = [[1,2],[3,4]]
arr = np.array(alist)
In [14]:
arr[0,1]
Out[14]:
In [15]:
arr[:,1] # access the last column
Out[15]:
In [16]:
arr[1,:] ## access the bottom row.
Out[16]:
In [17]:
arr = np.arange(5)
index = np.where(arr > 2) # Creating the index array
new_arr = arr[index] # Creating the desired array
new_arr
Out[17]:
In [18]:
new_arr = arr[arr > 2]
new_arr
Out[18]:
In [19]:
new_arr = np.delete(arr, index)
new_arr
Out[19]:
3. Boolean Statements¶
In [20]:
img1 = np.zeros((5, 5)) + 3
img1[1:3, 2:4] = 6
img1[3:5, 0:2] = 8
img1
Out[20]:
In [21]:
# filter out all values larger than 3 and less than 7
index1 = img1 > 3
index2 = img1 < 7
compoundindex = index1 & index2
img2 = np.copy(img1)
img2[compoundindex] = 0
img2
Out[21]:
In [22]:
index3 = (img1==8)
compoundindex2 = compoundindex | index3
img3 = np.copy(img1)
img3[compoundindex2] = 0
img3
Out[22]:
4. Read and Write Data¶
In [23]:
arr = np.loadtxt('dat1.txt')
arr
Out[23]:
In [24]:
np.savetxt('newdat1.txt', arr, delimiter=',', fmt='%.2f')
In [25]:
arr = np.loadtxt('dat2.txt',
dtype={'names':('name', 'weight','unit'),
'formats':('S5', 'f2','S2')})
arr
Out[25]:
5. Linear Algebra¶
In [26]:
A = np.matrix([[3,6,-5],
[1,-3,2],
[5,-1,4]])
B = np.matrix([[12],
[-2],
[10]])
x = A**(-1)*B
x
Out[26]:
In [27]:
a = np.array([[3,6,-5],
[1,-3,2],
[5,-1,4]])
b = np.array([12, -2, 10])
x = np.linalg.inv(a).dot(b)
x
# Although both methods works, use numpy.array whenever possible
Out[27]:
6. Statistics¶
In [28]:
x = np.random.randn(1000)
In [29]:
x.mean()
Out[29]:
In [30]:
x.std()
Out[30]:
In [31]:
x.var()
Out[31]:
In [32]:
np.median(x)
Out[32]:
In [33]:
np.mean(x)
Out[33]: