NumPy Library
In [4]:
#basic numpy option
import numpy as np
a = np.arange(15).reshape(3, 5)
a
a.shape
a.ndim
a.dtype.name
a.itemsize
a.size
type(a)
b = np.array([6, 7, 8])
type (b)
a = np.array([2,3,4])
a.dtype
b = np.array([1.2, 3.5, 5.1])
b.dtype
b = np.array([(1.5,2,3), (4,5,6),(4,6,7)])
c = np.array ( [ [1,2], [3,4] ], dtype=complex )
print (c)
np.zeros( (3,4) )
np.ones( (2,3,4), dtype=np.int16 )
print (np.empty( (2,3) ))
print (np.arange(10,30,5))
print (np.arange(1.2,3,0.2))
In [7]:
from numpy import pi
np.linspace(0,2,10) # 10 numbers from 0 to 2
Out[7]:
In [13]:
x = np.linspace( 0, 2*pi, 100 )
print (x)
f = np.sin(x)
print (f)
In [21]:
a = np.arange(6)
print (a)
b = np.arange(12).reshape(3,4)
print (b)
c= np.arange(24).reshape(2,4,3)
print("\n", c)
In [22]:
print(np.arange(10000))
In [25]:
print (np.arange(10000).reshape(100,100))
In [26]:
np.set_printoptions(thresold='nan')
In [32]:
a= np.array([21,30,40,50])
b= np.arange(4)
print ("\n", a)
c=a-b
print ("\n",c)
print ("\n",b**2)
10*np.sin(a)
print ("\n",a<35)
Out[32]:
In [39]:
A = np.array([[1,2],
[3,4]])
B = np.array([[5,6],
[7,8]])
print (A*B)
print ("\n",A.dot(B))
print ("\n", np.dot(A,B))
In [3]:
a = np.ones((2,3), dtype = int)
print (a)
b = np.random.random((2,3))
print ("\n",b)
a*=3
print (a)
b+=a
print (b)
a += b
In [12]:
a = np.ones(3, dtype=np.int32)
print (a)
b = np.linspace(0,pi,3)
print (b)
b.dtype.name
c=a+b
print (c)
d = np.exp(c*1j)
print (d)
d.dtype.name
Out[12]:
In [19]:
a=np.random.random((2,3))
print (a)
print (a.sum())
print (a.min())
print (a.max())
In [24]:
b = np.arange(12).reshape(3,4)
print (b)
print ("\n",b.sum(axis=0)) # sum of each row
print ("\n",b.min(axis=1)) # min of each row
print ("\n",b.cumsum(axis=1)) #cumulative sum along each row
In [28]:
B = np.arange (3)
print (B)
print (np.exp(B))
print (np.sqrt(B))
C = np.array ([2.,-1.,4.])
print (np.add(B,C))
In [42]:
a= np.arange(10)**3
print (a)
print (a[2])
print (a[2:5])
a[:6:2]=-1000 # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000
print (a)
b = a[ : :-1]
print (b)
for i in a:
print (i**(1/3.))
In [52]:
def f(x,y):
return 10*x+y
b = np.fromfunction(f,(5,4), dtype = int)
print (b)
print (b[2,3])
print (b[0:5, 0])
print (b[-2])
In [63]:
c = np.array([[[0,1,2],
[10,12,13]],
[[100,101,102],
[110,112,113]]])
print (c.shape)
print (c[0,...])
print (c[1])
print (c[...,1])
In [64]:
for row in b:
print (row)
In [66]:
for element in b.flat:
print (element)
In [70]:
a = np.floor(10*np.random.random((3,4)))
print (a)
a.shape
Out[70]:
In [71]:
a.ravel() # returns the array, flattened
Out[71]:
In [72]:
a.reshape (6,2)
Out[72]:
In [73]:
a.T
Out[73]:
In [74]:
a.T.shape
Out[74]:
In [75]:
a.shape
Out[75]:
In [76]:
a
Out[76]:
In [78]:
a.resize((2,6))
a
Out[78]:
In [79]:
a.reshape(3,-1)
Out[79]:
In [80]:
a = np.floor(10*np.random.random((2,2)))
a
Out[80]:
In [82]:
b = np.floor(10*np.random.random((2,2)))
b
Out[82]:
In [83]:
np.vstack ((a,b))
Out[83]:
In [84]:
np.hstack ((a,b))
Out[84]:
In [86]:
from numpy import newaxis
np.column_stack((a,b))
Out[86]:
In [88]:
a = np.array([4.,2.])
b = np.array([2.,8.])
a[:,newaxis]
Out[88]:
In [89]:
np.column_stack((a[:,newaxis],b[:,newaxis]))
Out[89]:
In [90]:
np.vstack((a[:,newaxis],b[:,newaxis]))
Out[90]:
In [91]:
a = np.floor(10*np.random.random((2,12)))
a
Out[91]:
In [92]:
np.hsplit(a,3)
Out[92]:
In [96]:
np.hsplit(a,(3,5,8))
Out[96]:
In [4]:
a= np.arange (12)
b=a
b is a
Out[4]:
In [5]:
b.shape = 3,4
a.shape
Out[5]:
In [6]:
def f(x):
print(id(x))
id(a)
f(a)
In [15]:
c= a.view()
c is a
print (c is a)
c.base is a
print (c.base is a)
c.flags.owndata
print (c.flags.owndata)
c.shape = 2,6
print (a.shape)
print (a)
print (c)
c[0,4] = 1234
print (a)
s = a[:,1:3]
s[:] = 10
print (a)
In [18]:
d = a.copy()
print (d is a)
print (d.base is a)
d[0,0] = 9999
print (a)
In [19]:
a = np.arange(12)**2
print (a)
i = np.array ([1,1,3,8,5])
a[i]
print (a[i])
In [20]:
j = np.array([[3,4], [9,7]])
a[j]
print (a[j])
In [23]:
palette = np.array ([[0,0,0],
[255,0,0],
[0,255,0],
[0,0,255],
[255,255,255]])
image = np.array ([[0,1,2,0],
[0,3,4,0]])
palette[image]
print (palette[image])
In [24]:
a= np.arange(12).reshape(3,4)
print (a)
In [3]:
a = np.arange(12).reshape(3,4)
print (a)
i = np.array( [ [0,1], # indices for the first dim of a
[1,2] ] )
j = np.array( [ [2,1], # indices for the second dim
[3,3] ] )
a[i,j] # i and j must have equal shape
print(a[i,j])
a[i,2]
print (a[i,2])
a[:,j] # i.e., a[ : , j]
print ("\n",a[:,j])
In [4]:
l = [i,j]
a[l] # equivalent to a[i,j]
print (a[l])
In [5]:
s = np.array( [i,j] )
# a[s] # not what we want
a[tuple(s)] # same as a[i,j]
print ("\n",a[tuple(s)])
In [6]:
time = np.linspace(20, 145, 5) # time scale
data = np.sin(np.arange(20)).reshape(5,4) # 4 time-dependent series
print (time)
print (data)
ind = data.argmax(axis=0) # index of the maxima for each series
print (ind)
time_max = time[ind] # times corresponding to the maxima
print (time_max)
data_max = data[ind, range(data.shape[1])] # data[ind[0],0], data[ind[1],1]...
print (data_max)
np.all(data_max == data.max(axis=0))
print (np.all(data_max == data.max(axis=0)))
In [7]:
a = np.arange(5)
print (a)
a[[1,3,4]] = 0
print (a)
# However, when the list of indices contains repetitions,
# the assignment is done several times, leaving behind the last value:
a = np.arange(5)
print ("\n",a)
a[[0,0,2]]=[1,2,3] # at index 0, 1 is placed. Then again at index 0, 1 is replaced by 2. And at index 2, 3 is placed.
print (a)
# This is reasonable enough, but watch out if you want to
# use Python’s += construct, as it may not do what you expect:
a = np.arange(5)
print ("\n",a)
a[[0,0,2]]+=1
print ("\n",a)
#Even though 0 occurs twice in the list of indices,
# the 0th element is only incremented once.
# This is because Python requires “a+=1” to be equivalent to “a = a + 1"
In [8]:
# Indexing with Boolean Arrays
a = np.arange(12).reshape(3,4)
b = a > 4
print (b) # b is a boolean with a's shape
print(a[b])
# This property can be very useful in assignments:
a[b] = 0 # All elements of 'a' higher than 4 become 0
print (a)
In [11]:
# You can look at the following example to see how
# to use boolean indexing to generate an image of the Mandelbrot set:
import numpy as np
import matplotlib.pyplot as plt
def mandelbrot( h,w, maxit=20 ):
"""Returns an image of the Mandelbrot fractal of size (h,w)."""
y,x = np.ogrid[ -1.4:1.4:h*1j, -2:0.8:w*1j ]
c = x+y*1j
z = c
divtime = maxit + np.zeros(z.shape, dtype=int)
for i in range(maxit):
z = z**2 + c
diverge = z*np.conj(z) > 2**2
div_now = diverge & (divtime==maxit)
divtime[div_now] = i
z[diverge] = 2
return divtime
plt.imshow(mandelbrot(400,400))
plt.show()
In [12]:
# The second way of indexing with booleans is more similar
# to integer indexing; for each dimension of the array
# we give a 1D boolean array selecting the slices we want:
a = np.arange(12).reshape(3,4)
b1 = np.array([False,True,True]) # first dim selection
b2 = np.array([True,False,True,False]) # second dim selection
a[b1,:] # selecting rows
print (a[b1,:])
a[b1] # same thing
print (a[b1])
a[:,b2] # selecting columns
print ("\n",a[:,b2])
a[b1,b2] # a weird thing to do
print ("\n",a[b1,b2])
Comments
Post a Comment