TMC Lab 02 - Supplementary Document.pdf - TMC Numpy...

This preview shows page 1 - 7 out of 20 pages.

TMC: Numpy & MatplotlibPresenter: Dr. Ha Viet Uyen Synh.
Overviewimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec
NUMPY LIBRARY
NumpyLibraryNumpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays.A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rankof the array; the shapeof an array is a tuple of integers giving the size of the array along each dimension.import numpy as npa = np.array([1, 2, 3]) # Create a rank 1 arrayprint(type(a)) # Prints "<class 'numpy.ndarray'>"print(a.shape) # Prints "(3,)"print(a[0], a[1], a[2]) # Prints "1 2 3"a[0] = 5 # Change an element of the arrayprint(a) # Prints "[5, 2, 3]"b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 arrayprint(b.shape) # Prints "(2, 3)"print(b[0, 0], b[0, 1], b[1, 0]) # Prints "1 2 4"
import numpy as npa = np.zeros((2,2)) # Create an array of all zerosprint(a) # Prints "[[ 0. 0.]# [ 0. 0.]]"b = np.ones((1,2)) # Create an array of all onesprint(b) # Prints "[[ 1. 1.]]"c = np.full((2,2), 7) # Create a constant arrayprint(c) # Prints "[[ 7. 7.]# [ 7. 7.]]"d = np.eye(2) # Create a 2x2 identity matrixprint(d) # Prints "[[ 1. 0.]# [ 0. 1.]]"e = np.random.random((2,2)) # Create an array filled with random valuesprint(e) # Might print "[[ 0.91940167 0.08143941]# [ 0.68744134 0.87236687]]"
Slicingimport numpy as np# Create the following rank 2 array with shape (3, 4)# [[ 1 2 3 4]# [ 5 6 7 8]# [ 9 10 11 12]]a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])# a[row, col]b = a[:2, 1:3]print(a[0, 1]) # Prints "2"b[0, 0] = 77 # b[0, 0] is the same piece of data as a[0, 1]print(a[0, 1]) # Prints "77“row_r1 = a[1, :] # Rank 1 view of the second row of arow_r2 = a[1:2, :] # Rank 2 view of the second row of aprint(row_r1, row_r1.shape) # Prints "[5 6 7 8] (4,)"print(row_r2, row_r2.shape) # Prints "[[5 6 7 8]] (1, 4)"

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture