In [2]:
import numpy as np
import scipy as sp
import numpy.linalg as la
import os
import os.path
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
% matplotlib inline
In [3]:
# create a 4x3 matrix of zeros
a=np.zeros((4,3))
a
Out[3]:
In [4]:
# the identity matrix
I = np.identity(3, dtype='float') # d stands for double
I
Out[4]:
In [5]:
# create a matrix
M=np.matrix([[1,2],[3,4]])
M
Out[5]:
In [6]:
# display type, shape, and size
type(M), M.shape, M.size
Out[6]:
In [7]:
# transpose of the matrix
M.T
Out[7]:
In [8]:
# another way to compute the transpose
np.transpose(M)
Out[8]:
In [9]:
# inverse of a matrix
M.I
Out[9]:
In [10]:
# another way to get the inverse
np.linalg.inv(M)
Out[10]:
In [11]:
# generate an array of equally spaced elements
L=np.linspace(0,1)
L
Out[11]:
In [12]:
type(L), L.shape, L.size
Out[12]:
In [13]:
# reshape the array - maintains the same size
LL=L.reshape((10,5))
LL
Out[13]:
In [14]:
# get the shape and size
LL.shape, LL.size
Out[14]:
In [15]:
# another array
np.linspace(0,1,20)
Out[15]:
In [16]:
# yet another line space array
x = np.linspace(0,2*np.pi)
x
Out[16]:
In [17]:
x.size
Out[17]:
In [18]:
# this produces an array
x=np.arange(15)
x
Out[18]:
In [19]:
# this one produces a list
y = list(range(15))
print(y)
In [20]:
type(x), type(y)
Out[20]:
In [21]:
a=np.arange(24).reshape(6,4)
a
Out[21]:
In [22]:
a.shape, a.size, a.ndim
Out[22]:
In [23]:
a.dtype, a.dtype.name, a.itemsize, type(a)
Out[23]:
In [24]:
b = np.array( [ (1.5,2,3), (4,5,6) ] )
b
Out[24]:
In [25]:
c = np.array( [ [1,2], [3,4] ], dtype=complex )
c
Out[25]:
In [26]:
np.arange( 10, 30, 5 )
Out[26]:
In [27]:
np.arange(0,15,1)
Out[27]:
In [28]:
np.arange( 0, 2, 0.3 )
Out[28]:
In [29]:
np.arange(15)
Out[29]:
In [30]:
print(np.arange(10000))
In [31]:
print(np.arange(10000).reshape(100,100))
In [32]:
x=np.arange(10000)
x[1000:1100]
Out[32]:
In [33]:
a = np.array( [20,30,40,50] )
b = np.arange( 4 )
c = a-b
print (a)
print (b)
print (c)
In [34]:
L=[1,2,3]
L**2
In [35]:
b**2
Out[35]:
In [36]:
10*np.sin(a)
Out[36]:
In [37]:
a < 35
Out[37]:
In [38]:
A = np.array( [[1,1],[0,1]] )
In [39]:
B = np.array( [[2,0],[3,4]] )
In [40]:
A*B # element by element multi
Out[40]:
In [41]:
np.dot(A,B) # matrix multiply
Out[41]:
In [42]:
a = np.ones((2,3), dtype=int)
b = np.random.random((2,3))
print (a)
print (b)
In [43]:
a *= 3 # a = a * 3
In [44]:
b += a # b = b + a
b
Out[44]:
In [45]:
a += b
a
In [46]:
a = a + b
a
Out[46]:
In [80]:
a = np.random.random((2,3))
In [81]:
b = np.arange(12).reshape(3,4)
b
Out[81]:
In [82]:
b.sum(axis=0) # sum across columns
Out[82]:
In [83]:
b.min(axis=1)
Out[83]:
In [84]:
b.cumsum(axis=1)
Out[84]:
In [85]:
B = np.arange(3)
In [86]:
np.exp(B)
Out[86]:
In [87]:
np.sqrt(B)
Out[87]:
In [88]:
C = np.array([2., -1., 4.])
In [89]:
np.add(B, C)
Out[89]:
In [90]:
a = np.arange(10)**3
a
Out[90]:
In [91]:
a[2:]
Out[91]:
In [92]:
a[2:5]
Out[92]:
In [93]:
a[:6:2] = -1000 # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000
In [94]:
a[ : :-1] # reversed a
Out[94]:
In [96]:
a = np.floor(10*np.random.random((3,4)))
In [97]:
a.shape
Out[97]:
In [98]:
a.ravel() # flatten the array
Out[98]:
In [99]:
a.shape = (6, 2)
In [100]:
a.transpose()
Out[100]:
In [101]:
a.resize((2,6))
In [102]:
a.reshape(3,-1)
Out[102]:
In [105]:
a = np.floor(10*np.random.random((2,2)))
In [106]:
b = np.floor(10*np.random.random((2,2)))
In [107]:
np.vstack((a,b))
Out[107]:
In [108]:
np.hstack((a,b))
Out[108]:
In [109]:
np.column_stack((a,b))
Out[109]:
In [111]:
a=np.array([4.,2.])
b=np.array([2.,8.])
In [113]:
a[:,np.newaxis] # This allows to have a 2D columns vector
Out[113]:
In [115]:
np.column_stack((a[:,np.newaxis],b[:,np.newaxis]))
Out[115]:
In [116]:
np.vstack((a[:,np.newaxis],b[:,np.newaxis])) # The behavior of vstack is different
Out[116]:
In [117]:
a = np.floor(10*np.random.random((2,12)))
In [118]:
np.hsplit(a,3) # Split a into 3
Out[118]:
In [119]:
np.hsplit(a,(3,4)) # Split a after the third and the fourth column
Out[119]:
In [120]:
a = np.arange(12)
b=a
In [121]:
b is a
Out[121]:
In [122]:
b.shape = 3,4
In [123]:
a.shape
Out[123]:
In [126]:
def f(x):print (id(x))
In [128]:
id(a)
Out[128]:
In [129]:
f(a)
In [130]:
c = a.view()
In [131]:
c is a
Out[131]:
In [132]:
c.base is a # c is a view of the data owned by a
Out[132]:
In [133]:
c.flags.owndata
Out[133]:
In [134]:
c.shape = 2,6
In [135]:
a.shape
Out[135]:
In [136]:
c[0,4] = 1234
a
Out[136]:
In [137]:
s = a[ : , 1:3] # spaces added for clarity; could also be written "s = a[:,1:3]"
s
Out[137]:
In [138]:
s[:] = 10 # s[:] is a view of s. Note the difference between s=10 and s[:]=10
In [139]:
d = a.copy()
d is a
Out[139]:
In [140]:
d.base is a # d doesn't share anything with a
Out[140]:
In [141]:
a = np.random.random((5,6))
b = np.random.random((5,6))
print('a=',a)
print('b=',b)
In [12]:
# write a to a text file. a will be unravelled and written as one line
a.tofile(os.path.join('data', 'out01.txt'), sep=",")
In [ ]:
# save an array to a binary file in NumPy .npy format
np.savetxt(os.path.join('data', 'out02.txt'), a)
In [ ]:
# save an array to a binary file in NumPy .npy format
np.savetxt(os.path.join('data', 'out03.txt'), (a.ravel(), b.ravel()))
In [ ]:
# save an array to a binary file in NumPy .npy format
np.savetxt(os.path.join('data', 'out04.txt'), b, fmt='%1.4e')
In [ ]:
# Save an array to a binary file in NumPy .npy format.
np.save(os.path.join('data', 'out05'), a)
np.load(os.path.join('data', 'out05.npy'))
In [ ]:
# Save several arrays into a single file in uncompressed .npz format
np.savez(os.path.join('data', 'out06'), a,b)
npzfile = np.load(os.path.join('data', 'out06.npz'))
In [4]:
np.savez(os.path.join('data', 'out07'), a,b, avg=a, std=b)
npzfile = np.load(os.path.join('data', 'out07.npz'))
In [ ]:
# Save several arrays into a single file in uncompressed .npz format
np.savez(os.path.join('data', 'out08'), b=b, c=a+b)
npzfile = np.load(os.path.join('data', 'out08.npz'))
In [ ]:
# Save several arrays into a single file in uncompressed .npz format
np.savez_compressed(os.path.join('data', 'out8'), b=b, c=a+b)
npzfile = np.load(os.path.join('data', 'out08.npz'))
In [7]:
a = np.fromstring('0 1 2 3 4 5 6 7 8 9 10', dtype=int, sep=' ')
print(a)
In [ ]:
a = np.fromstring('0 1 2 3 4 5 6 7 8 9 10', dtype=int, sep=' ', count=5)
print(a)
In [ ]:
a.tolist()
In [6]:
a = np.fromstring('\x01\x02\x03\x04\x05', dtype=np.uint8, count=3)
print(a)
In [8]:
np.fromstring('1, 2', dtype=int, sep=',')
Out[8]:
In [8]:
a = np.array([1, 2])
a.tolist()
Out[8]:
In [11]:
a = np.array([[1, 2], [3, 4]])
In [12]:
list(a)
Out[12]:
In [13]:
a.tolist
Out[13]:
In [14]:
a = np.genfromtxt('data'+os.sep+'file.txt', dtype=int,comments='#',
delimiter=',', skip_header=1,missing='', missing_values='N/A')
In [15]:
a
Out[15]:
In [16]:
a = np.genfromtxt('data'+os.sep+'file.txt',comments='#',
delimiter=',', skip_header=1,missing='', missing_values='N/A')
In [17]:
a
Out[17]:
In [18]:
a = np.genfromtxt('data'+os.sep+'file.txt', dtype=int,comments='#',
delimiter=',', skip_header=1,missing='', missing_values=10)
In [19]:
a
Out[19]:
In [20]:
a=np.arange(100)
a[::3]
Out[20]:
In [21]:
a[10:88:3]
Out[21]:
In [22]:
a[::-1]
Out[22]:
In [ ]:
file_name = os.path.join('data', 'bindata.bin')
fin = open(file_name, 'rb')
data = np.fromfile(fin,dtype=np.float32,count=5)
for num in data:
print ('%d'),%num
In [ ]:
data2 = np.fromfile(fin,dtype=np.float32,count=6)
print (data2)
type(data2)
In [ ]:
data3= np.fromfile(fin,dtype=np.float32,count=4)
for num in data3:
print '%e' %num
In [ ]:
data4 = np.fromfile(fin,dtype=np.float32,count=-1)
print data4
print len(data4)
fin.close()
In [ ]:
with open(file_name, "rb") as fin:
fin.seek(4)
ncols = int(np.fromfile(fin, dtype=np.float32, count = 1))
print 'Num Cols: ', int(ncols)
#go back to the beginning of the file
fin.seek(0)
pfluc_dtype = np.dtype([
("N", np.float32),
("ncols", np.float32),
("Q", np.float32),
("U", np.float32),
("fs", np.float32),
#array with ncols
("x", (np.float32, (ncols))),
("L", np.float32),
("W", np.float32),
("D", np.float32),
("pRef", np.float32)
#
])
data = np.fromfile(fin, dtype=pfluc_dtype, count =1)
print 'Data read using "np.fromfile": '
print 'N', pfluc_dtype.fields['N'], ': ', data['N']
print 'ncols', pfluc_dtype.fields['ncols'], ': ', data['ncols']
print 'Q', pfluc_dtype.fields['Q'], ': ', data['Q']
print 'U', pfluc_dtype.fields['U'], ': ', data['U']
print 'fs', pfluc_dtype.fields['fs'], ': ', data['fs']
print 'x', pfluc_dtype.fields['x'], ': ', data['x']
print 'L', pfluc_dtype.fields['L'], ': ', data['L']
print 'W', pfluc_dtype.fields['W'], ': ', data['W']
print 'D', pfluc_dtype.fields['D'], ': ', data['D']
print 'p Ref', pfluc_dtype.fields['pRef'], ': ', data['pRef']
In [ ]:
import matplotlib.pyplot as plt
plt.plot(data4[0:int(data['N'])])
In [ ]:
plt.plot(data4[::6])
In [ ]:
a = np.genfromtxt('data'+os.sep+'file.txt', dtype=int,comments='#',
delimiter=',', skip_header=1,missing='', missing_values='N/A')
In [ ]:
a = np.genfromtxt('data'+os.sep+'file.txt',comments='#',
delimiter=',', skip_header=1,missing='', missing_values='N/A')
In [ ]:
a = np.genfromtxt('data'+os.sep+'file.txt', dtype=int,comments='#',
delimiter=',', skip_header=1,missing='', missing_values=10)
In [24]:
img = mpimg.imread('images'+os.sep+'stinkbug.png')
In [25]:
img
Out[25]:
In [47]:
img2 = mpimg.imread('images'+os.sep+'315px-Chaetodon_melannotus_edit4.jpg')
In [48]:
imgplot = plt.imshow(img)
plt.show()
In [49]:
lum_img = img[:,:,0]
imgplot = plt.imshow(lum_img)
plt.show()
In [50]:
imgplot = plt.imshow(lum_img)
imgplot.set_cmap('hot')
#imgplot.set_cmap('spectral')
plt.colorbar()
plt.show()
In [51]:
plt.hist(lum_img.flatten(), 256, range=(0.0,1.0), fc='k', ec='k')
plt.show()
In [52]:
img2
Out[52]:
In [53]:
imgplot2 = plt.imshow(img2)
plt.show()