2/28/2019 Numpy+Basics
Numpy Array
In [2]: import numpy as np
np.array([1, 2, 3])
Out[2]: array([1, 2, 3])
In [3]: #Upcasting:
In [4]: np.array([1, 2, 3.0])
Out[4]: array([ 1., 2., 3.])
In [5]: #two dimensions
In [6]: np.array([[1, 2], [3, 4]])
Out[6]: array([[1, 2],
[3, 4]])
In [7]: #Minimum dimensions 2:
In [8]: np.array([1, 2, 3], ndmin=2)
Out[8]: array([[1, 2, 3]])
In [9]: #dtype
In [10]: np.array([1, 2, 3], dtype=complex)
Out[10]: array([ 1.+0.j, 2.+0.j, 3.+0.j])
In [11]: #Data-type consisting of more than one element:
In [12]: x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
In [13]: x['a']
Out[13]: array([1, 3])
In [14]: #Creating an array from sub-classes:
In [15]: np.array(np.mat('1 2; 3 4'))
Out[15]: array([[1, 2],
[3, 4]])
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 1/50
2/28/2019 Numpy+Basics
In [16]: np.array(np.mat('1 2; 3 4'), subok=True)
Out[16]: matrix([[1, 2],
[3, 4]])
numpy.asarray
In [17]: #Convert the input to an array.
In [18]: #Convert a list into an array:
In [21]: a = [1, 2]
In [22]: np.asarray(a)
Out[22]: array([1, 2])
In [23]: a = np.array([1, 2]) #Existing arrays are not copied
In [24]: np.asarray(a) is a
Out[24]: True
In [25]: #If dtype is set, array is copied only if dtype does not match:
In [26]: a = np.array([1, 2], dtype=np.float32)
In [27]: np.asarray(a, dtype=np.float32) is a
Out[27]: True
In [28]: np.asarray(a, dtype=np.float64) is a
Out[28]: False
In [29]: # ndarray subclasses are not passed through
In [30]: issubclass(np.matrix, np.ndarray)
Out[30]: True
In [31]: a = np.matrix([[1, 2]])
In [32]: np.asarray(a) is a
Out[32]: False
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 2/50
2/28/2019 Numpy+Basics
In [33]: np.asanyarray(a) is a
Out[33]: True
numpy.asanyarray
In [35]: a = [1, 2]
np.asanyarray(a)
Out[35]: array([1, 2])
In [36]: a = np.matrix([1, 2])
In [37]: np.asanyarray(a) is a
Out[37]: True
#numpy.copy
In [39]: np.array(a, copy=True)
Out[39]: array([[1, 2]])
In [40]: #Create an array x, with a reference y and a copy z:
In [41]: x = np.array([1, 2, 3])
In [42]: y = x
In [43]: z = np.copy(x)
In [44]: #when we modify x, y changes, but not z
In [45]: x[0] = 10
In [46]: x[0] == y[0]
Out[46]: True
In [47]: x[0] == z[0]
Out[47]: False
Read data from file
In [48]: #Construct an array from data in a text or binary file.A highly efficient way of
#known data-type, as well as parsing simply formatted text files. Data written us
#read using this function.
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 3/50
2/28/2019 Numpy+Basics
In [49]: x
Out[49]: array([10, 2, 3])
In [50]: import os
In [55]: np.fromfile('C:/Datasets/College_Data')
Out[55]: array([ 2.50400331e+262, 5.32000938e+232, 5.81323893e+170, ...,
7.58796605e-096, 5.04659914e-038, 2.10613154e-052])
In [57]: np.save('C:/Datasets/College_Data', x)
numpy.fromfunction
In [58]: #Construct an array by executing a function over each coordinate.
In [59]: np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
Out[59]: array([[ True, False, False],
[False, True, False],
[False, False, True]], dtype=bool)
In [60]: np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
Out[60]: array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
In [61]: #Create a new 1-dimensional array from an iterable object.
In [62]: iterable = (x*x for x in range(5))
In [63]: np.fromiter(iterable, float)
Out[63]: array([ 0., 1., 4., 9., 16.])
In [64]: #A new 1-D array initialized from text data in a string
In [65]: np.fromstring('1 2', dtype=int, sep=' ')
Out[65]: array([1, 2])
In [68]: np.fromstring('1, 2', dtype=int, sep=',')
Out[68]: array([1, 2])
Load data from a text file
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 4/50
2/28/2019 Numpy+Basics
In [69]: from io import StringIO
In [70]: c = StringIO("0 1\n2 3")
In [71]: np.loadtxt(c)
Out[71]: array([[ 0., 1.],
[ 2., 3.]])
In [72]: d = StringIO("M 21 72\nF 35 58")
In [73]: np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),
... 'formats': ('S1', 'i4', 'f4')})
Out[73]: array([(b'M', 21, 72.), (b'F', 35, 58.)],
dtype=[('gender', 'S1'), ('age', '<i4'), ('weight', '<f4')])
In [74]: c = StringIO("1,0,2\n3,0,4")
In [75]: x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True)
In [76]: x
Out[76]: array([ 1., 3.])
In [77]: y
Out[77]: array([ 2., 4.])
#Parameters::
'''fname : file, str, or pathlib.Path:::File, filename, or generator to read.
If the filename extension is .gz or .bz2, the file is first decompressed. Note
that generators should return byte strings for Python 3k.
dtype : data-type, optional:::Data-type of the resulting array; default: float.
If this is a structured data-type, the resulting array will be 1-dimensional,
and each row will be interpreted as an element of the array. In this case, the
number of columns used must match the number of fields in the data-type.
comments : str or sequence of str, optional:::The characters or list of
characters used to indicate the start of a comment. For backwards
compatibility, byte strings will be decoded as ‘latin1’. The default is ‘#’.
delimiter : str, optional:::The string used to separate values. For backwards
compatibility, byte strings will be decoded as ‘latin1’. The default is
whitespace.
converters : dict, optional:::A dictionary mapping column number to a function
that will convert that column to a float. E.g., if column 0 is a date string:
converters = {0: datestr2num}. Converters can also be used to provide a default
value for missing data (but see also genfromtxt): converters = {3: lambda s:
float(s.strip() or 0)}. Default: None.
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 5/50
2/28/2019 Numpy+Basics
skiprows : int, optional:::Skip the first skiprows lines; default: 0.
usecols : int or sequence, optional:::Which columns to read, with 0 being the
first. For example, usecols = (1,4,5) will extract the 2nd, 5th and 6th
columns. The default, None, results in all columns being read.
Changed in version 1.11.0: When a single column has to be read it is possible
to use an integer instead of a tuple. E.g usecols = 3 reads the fourth column
the same way as usecols = (3,)` would.
unpack : bool, optional:::If True, the returned array is transposed, so that
arguments may be unpacked using x, y, z = loadtxt(...). When used with a
structured data-type, arrays are returned for each field. Default is False.
ndmin : int, optional:::The returned array will have at least ndmin dimensions.
Otherwise mono-dimensional axes will be squeezed. Legal values: 0 (default), 1
or 2. New in version 1.6.0.
encoding : str, optional:::Encoding used to decode the inputfile. Does not
apply to input streams. The special value ‘bytes’ enables backward
compatibility workarounds that ensures you receive byte arrays as results if
possible and passes latin1 encoded strings to converters. Override this value
to receive unicode arrays and pass strings as input to converters. If set to
None the system default is used. The default value is ‘bytes’.'''
In [79]: # How to create create a record array from a (flat) list of arrays
In [80]: x1=np.array([1,2,3,4])
In [81]: x2=np.array(['a','dd','xyz','12'])
In [82]: x3=np.array([1.1,2,3,4])
In [83]: r = np.core.records.fromarrays([x1,x2,x3],names='a,b,c')
In [84]: print(r[1])
(2, 'dd', 2.0)
x1[1]=34
In [85]: r.a
Out[85]: array([1, 2, 3, 4])
data types
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 6/50
2/28/2019 Numpy+Basics
In [86]: my_list = [1,2,3]
import numpy as np
arr = np.array(my_list)
print("Type/Class of this object:",type(arr))
print("Here is the vector\n--------------------\n",arr)
Type/Class of this object: <class 'numpy.ndarray'>
Here is the vector
--------------------
[1 2 3]
In [87]: my_mat = [[1,2,3],[4,5,6],[7,8,9]]
mat = np.array(my_mat)
print("Type/Class of this object:",type(mat))
print("Here is the matrix\n----------\n",mat,"\n----------")
print("Dimension of this matrix: ",mat.ndim,sep='') #ndim gives the dimensison, 2
print("Size of this matrix: ", mat.size,sep='') #size gives the total number of e
print("Shape of this matrix: ", mat.shape,sep='') #shape gives the number of elem
print("Data type of this matrix: ", mat.dtype,sep='') #dtype gives the data type
Type/Class of this object: <class 'numpy.ndarray'>
Here is the matrix
----------
[[1 2 3]
[4 5 6]
[7 8 9]]
----------
Dimension of this matrix: 2
Size of this matrix: 9
Shape of this matrix: (3, 3)
Data type of this matrix: int32
In [88]: my_mat = [[1.1,2,3],[4,5.2,6],[7,8.3,9]]
mat = np.array(my_mat)
print("Data type of the modified matrix: ", mat.dtype,sep='') #dtype gives the da
print("\n\nEven tuples can be converted to ndarrays...")
Data type of the modified matrix: float64
Even tuples can be converted to ndarrays...
In [89]: b = np.array([(1.5,2,3), (4,5,6)])
print("We write b = np.array([(1.5,2,3), (4,5,6)])")
print("Matrix made from tuples, not lists\n-------------------------------------
print(b)
We write b = np.array([(1.5,2,3), (4,5,6)])
Matrix made from tuples, not lists
---------------------------------------
[[ 1.5 2. 3. ]
[ 4. 5. 6. ]]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 7/50
2/28/2019 Numpy+Basics
arange and linspace
In [90]: print("A series of numbers:",np.arange(5,16)) # A series of numbers from low to h
A series of numbers: [ 5 6 7 8 9 10 11 12 13 14 15]
In [91]: print("Numbers spaced apart by 2:",np.arange(0,11,2)) # Numbers spaced apart by 2
Numbers spaced apart by 2: [ 0 2 4 6 8 10]
In [92]: print("Numbers spaced apart by float:",np.arange(0,11,2.5)) # Numbers spaced apar
Numbers spaced apart by float: [ 0. 2.5 5. 7.5 10. ]
In [93]: print("Every 5th number from 50 in reverse order\n",np.arange(50,-1,-5))
Every 5th number from 50 in reverse order
[50 45 40 35 30 25 20 15 10 5 0]
In [94]: print("21 linearly spaced numbers between 1 and 5\n-----------------------------
print(np.linspace(1,5,21))
21 linearly spaced numbers between 1 and 5
--------------------------------------------
[ 1. 1.2 1.4 1.6 1.8 2. 2.2 2.4 2.6 2.8 3. 3.2 3.4 3.6 3.8
4. 4.2 4.4 4.6 4.8 5. ]
Matrix creation
In [96]: print("Vector of zeroes\n---------------------")
print(np.zeros(5))
Vector of zeroes
---------------------
[ 0. 0. 0. 0. 0.]
In [97]: print("Matrix of zeroes\n--------------------")
print(np.zeros((3,4))) # Notice Tuples
Matrix of zeroes
--------------------
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
In [98]: print("Vector of ones\n---------------------")
print(np.ones(5))
Vector of ones
---------------------
[ 1. 1. 1. 1. 1.]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 8/50
2/28/2019 Numpy+Basics
In [99]: print("Matrix of ones\n---------------------")
print(np.ones((5,2))) # Note matrix dimension specified by Tuples
Matrix of ones
---------------------
[[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]]
In [100]: print("Matrix of 5's\n---------------------")
print(5*np.ones((3,5)))
Matrix of 5's
---------------------
[[ 5. 5. 5. 5. 5.]
[ 5. 5. 5. 5. 5.]
[ 5. 5. 5. 5. 5.]]
In [101]: print("Empty matrix\n-------------\n", np.empty((3,5)))
Empty matrix
-------------
[[ 5. 5. 5. 5. 5.]
[ 5. 5. 5. 5. 5.]
[ 5. 5. 5. 5. 5.]]
In [102]: mat1 = np.eye(4)
print("Identity matrix of dimension", mat1.shape)
print(mat1)
Identity matrix of dimension (4, 4)
[[ 1. 0. 0. 0.]
[ 0. 1. 0. 0.]
[ 0. 0. 1. 0.]
[ 0. 0. 0. 1.]]
In [103]: np.arange(3)
Out[103]: array([0, 1, 2])
In [104]: np.arange(3.0)
Out[104]: array([ 0., 1., 2.])
In [105]: np.arange(3,7)
Out[105]: array([3, 4, 5, 6])
In [106]: np.arange(3,7,2)
Out[106]: array([3, 5])
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 9/50
2/28/2019 Numpy+Basics
In [107]: np.linspace(2.0, 3.0, num=5)
Out[107]: array([ 2. , 2.25, 2.5 , 2.75, 3. ])
In [108]: np.linspace(2.0, 3.0, num=5, endpoint=False)
Out[108]: array([ 2. , 2.2, 2.4, 2.6, 2.8])
In [109]: np.linspace(2.0, 3.0, num=5, retstep=True)
Out[109]: (array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
In [110]: #Return numbers spaced evenly on a log scale.
In [112]: np.logspace(2.0, 3.0, num=4)
Out[112]: array([ 100. , 215.443469 , 464.15888336, 1000. ])
In [113]: np.logspace(2.0, 3.0, num=4, endpoint=False)
Out[113]: array([ 100. , 177.827941 , 316.22776602, 562.34132519])
In [114]: np.logspace(2.0, 3.0, num=4, base=2.0)
Out[114]: array([ 4. , 5.0396842 , 6.34960421, 8. ])
In [115]: #Extract a diagonal or construct a diagonal array.
In [116]: x = np.arange(9).reshape((3,3))
In [117]: x
Out[117]: array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
In [118]: np.diag(x)
Out[118]: array([0, 4, 8])
In [119]: np.diag(x, k=1)
Out[119]: array([1, 5])
In [120]: np.diag(x, k=-1)
Out[120]: array([3, 7])
In [121]: np.diag(np.diag(x))
Out[121]: array([[0, 0, 0],
[0, 4, 0],
[0, 0, 8]])
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 10/50
2/28/2019 Numpy+Basics
In [122]: #Create a two-dimensional array with the flattened input as a diagonal.
In [123]: np.diagflat([[1,2], [3,4]])
Out[123]: array([[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]])
In [124]: np.diagflat([1,2], 1)
Out[124]: array([[0, 1, 0],
[0, 0, 2],
[0, 0, 0]])
In [125]: #An array with ones at and below the given diagonal and zeros elsewhere.
In [126]: np.tri(3, 5, 2, dtype=int)
Out[126]: array([[1, 1, 1, 0, 0],
[1, 1, 1, 1, 0],
[1, 1, 1, 1, 1]])
In [127]: np.tri(3, 5, -1)
Out[127]: array([[ 0., 0., 0., 0., 0.],
[ 1., 0., 0., 0., 0.],
[ 1., 1., 0., 0., 0.]])
In [128]: #return a Lower triangle of an array.
In [129]: np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
Out[129]: array([[ 0, 0, 0],
[ 4, 0, 0],
[ 7, 8, 0],
[10, 11, 12]])
In [130]: #return Upper triangle of an array.
In [131]: np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
Out[131]: array([[ 1, 2, 3],
[ 4, 5, 6],
[ 0, 8, 9],
[ 0, 0, 12]])
Random number generation
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 11/50
2/28/2019 Numpy+Basics
In [132]: print("Random number generation (from Uniform distribution)")
print(np.random.rand(2,3)) # 2 by 3 matrix with random numbers ranging from 0 to
Random number generation (from Uniform distribution)
[[ 0.17992539 0.77466986 0.40346943]
[ 0.27872765 0.38668577 0.23248726]]
In [133]: print("Numbers from Normal distribution with zero mean and standard deviation 1 i
print(np.random.randn(4,3))
Numbers from Normal distribution with zero mean and standard deviation 1 i.e. s
tandard normal
[[-0.7234741 0.32885333 -0.60040597]
[ 0.54863879 1.76326167 -0.97475272]
[ 0.30910746 0.30583897 0.95082336]
[-1.52208987 0.47583592 1.18738672]]
In [134]: print("Random integer vector:",np.random.randint(1,100,10)) #randint (low, high,
print ("\nRandom integer matrix")
Random integer vector: [95 82 41 43 96 97 27 45 30 45]
Random integer matrix
In [135]: print(np.random.randint(1,100,(4,4))) #randint (low, high, # of samples to be dra
print("\n20 samples drawn from a dice throw:",np.random.randint(1,7,20)) # 20 sam
[[11 12 83 23]
[24 62 82 50]
[ 2 3 83 76]
[14 43 57 40]]
20 samples drawn from a dice throw: [6 3 2 3 3 2 1 2 4 2 5 2 2 1 4 1 4 3 3 2]
Reshaping
In [136]: from numpy.random import randint as ri
a = ri(1,100,30)
b = a.reshape(2,3,5)
c = a.reshape(6,5)
In [137]: print ("Shape of a:", a.shape)
print ("Shape of b:", b.shape)
print ("Shape of c:", c.shape)
Shape of a: (30,)
Shape of b: (2, 3, 5)
Shape of c: (6, 5)
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 12/50
2/28/2019 Numpy+Basics
In [138]: print("\na looks like\n",'-'*20,"\n",a,"\n",'-'*20)
print("\nb looks like\n",'-'*20,"\n",b,"\n",'-'*20)
print("\nc looks like\n",'-'*20,"\n",c,"\n",'-'*20)
a looks like
--------------------
[22 5 3 82 52 48 38 5 4 75 45 74 34 58 36 54 12 18 70 80 50 82 33 50 67
33 75 32 17 35]
--------------------
b looks like
--------------------
[[[22 5 3 82 52]
[48 38 5 4 75]
[45 74 34 58 36]]
[[54 12 18 70 80]
[50 82 33 50 67]
[33 75 32 17 35]]]
--------------------
c looks like
--------------------
[[22 5 3 82 52]
[48 38 5 4 75]
[45 74 34 58 36]
[54 12 18 70 80]
[50 82 33 50 67]
[33 75 32 17 35]]
--------------------
In [139]: A = ri(1,100,10) # Vector of random interegrs
print("\nVector of random integers\n",'-'*50,"\n",A)
print("\nHere is the sorted vector\n",'-'*50,"\n",np.sort(A, kind='mergesort'))
Vector of random integers
--------------------------------------------------
[64 93 37 58 33 61 30 19 68 25]
Here is the sorted vector
--------------------------------------------------
[19 25 30 33 37 58 61 64 68 93]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 13/50
2/28/2019 Numpy+Basics
In [140]: M = ri(1,100,25).reshape(5,5) # Matrix of random interegrs
print("\n5x5 Matrix of random integers\n",'-'*50,"\n",M)
print("\nHere is the sorted matrix along each row\n",'-'*50,"\n",np.sort(M, kind=
print("\nHere is the sorted matrix along each column\n",'-'*50,"\n",np.sort(M, ax
5x5 Matrix of random integers
--------------------------------------------------
[[23 72 6 36 36]
[61 15 43 94 70]
[30 77 75 85 76]
[48 46 34 26 68]
[16 84 33 53 57]]
Here is the sorted matrix along each row
--------------------------------------------------
[[ 6 23 36 36 72]
[15 43 61 70 94]
[30 75 76 77 85]
[26 34 46 48 68]
[16 33 53 57 84]]
Here is the sorted matrix along each column
--------------------------------------------------
[[16 15 6 26 36]
[23 46 33 36 57]
[30 72 34 53 68]
[48 77 43 85 70]
[61 84 75 94 76]]
In [141]: print("Max of a:", a.max())
print("Max of b:", b.max())
Max of a: 82
Max of b: 82
In [142]: print("Max of a location:", a.argmax())
print("Max of b location:", b.argmax())
print("Max of c location:", b.argmax())
Max of a location: 3
Max of b location: 3
Max of c location: 3
Indexing and slicing
In [143]: arr = np.arange(0,11)
print("Array:",arr)
Array: [ 0 1 2 3 4 5 6 7 8 9 10]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 14/50
2/28/2019 Numpy+Basics
In [144]: print("Element at 7th index is:", arr[7])
Element at 7th index is: 7
In [145]: print("Elements from 3rd to 5th index are:", arr[3:6])
Elements from 3rd to 5th index are: [3 4 5]
In [146]: print("Elements up to 4th index are:", arr[:4])
Elements up to 4th index are: [0 1 2 3]
In [147]: print("Elements from last backwards are:", arr[-1::-1])
Elements from last backwards are: [10 9 8 7 6 5 4 3 2 1 0]
In [148]: print("3 Elements from last backwards are:", arr[-1:-6:-2])
3 Elements from last backwards are: [10 8 6]
In [149]: arr = np.arange(0,21,2)
print("New array:",arr)
New array: [ 0 2 4 6 8 10 12 14 16 18 20]
In [150]: print("Elements at 2nd, 4th, and 9th index are:", arr[[2,4,9]]) # Pass a list as
Elements at 2nd, 4th, and 9th index are: [ 4 8 18]
In [151]: mat = np.array(ri(10,100,15)).reshape(3,5)
print("Matrix of random 2-digit numbers\n--------------------------------\n",mat
Matrix of random 2-digit numbers
--------------------------------
[[47 77 92 69 39]
[39 64 49 17 53]
[75 38 48 99 95]]
In [152]: print("\nDouble bracket indexing\n------------------------")
print("Element in row index 1 and column index 2:", mat[1][2])
Double bracket indexing
------------------------
Element in row index 1 and column index 2: 49
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 15/50
2/28/2019 Numpy+Basics
In [153]: print("\nSingle bracket with comma indexing\n----------------------------------"
print("Element in row index 1 and column index 2:", mat[1,2])
print("\nRow or column extract\n----------------------")
Single bracket with comma indexing
----------------------------------
Element in row index 1 and column index 2: 49
Row or column extract
----------------------
In [154]: print("Entire row at index 2:", mat[2])
print("Entire column at index 3:", mat[:,3])
Entire row at index 2: [75 38 48 99 95]
Entire column at index 3: [69 17 99]
In [155]: print("\nSubsetting sub-matrices\n--------------------------")
print("Matrix with row indices 1 and 2 and column indices 3 and 4\n", mat[1:3,3:5
Subsetting sub-matrices
--------------------------
Matrix with row indices 1 and 2 and column indices 3 and 4
[[17 53]
[99 95]]
In [156]: print("Matrix with row indices 0 and 1 and column indices 1 and 3\n", mat[0:2,[1,
Matrix with row indices 0 and 1 and column indices 1 and 3
[[77 69]
[64 17]]
Subseting
In [157]: mat = np.array(ri(10,100,15)).reshape(3,5)
print("Matrix of random 2-digit numbers\n--------------------------------\n",mat
Matrix of random 2-digit numbers
--------------------------------
[[92 22 93 19 15]
[84 82 21 82 44]
[48 69 69 60 39]]
In [158]: print ("Elements greater than 50\n", mat[mat>50])
Elements greater than 50
[92 93 84 82 82 69 69 60]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 16/50
2/28/2019 Numpy+Basics
Slicing
In [159]: mat = np.array([[11,12,13],[21,22,23],[31,32,33]])
print("Original matrix")
print(mat)
Original matrix
[[11 12 13]
[21 22 23]
[31 32 33]]
In [161]: mat_slice = mat[:2,:2]
print ("\nSliced matrix")
print(mat_slice)
print ("\nChange the sliced matrix")
Sliced matrix
[[11 12]
[21 22]]
Change the sliced matrix
In [163]: mat_slice[0,0] = 1000
print (mat_slice)
[[1000 12]
[ 21 22]]
In [164]: print("\nBut the original matrix? WHOA! It got changed too!")
print(mat)
But the original matrix? WHOA! It got changed too!
[[1000 12 13]
[ 21 22 23]
[ 31 32 33]]
In [165]: # Little different way to create a copy of the slixed matrix
print ("\nDoing it again little differently now...\n")
mat = np.array([[11,12,13],[21,22,23],[31,32,33]])
print("Original matrix")
print(mat)
Doing it again little differently now...
Original matrix
[[11 12 13]
[21 22 23]
[31 32 33]]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 17/50
2/28/2019 Numpy+Basics
In [166]: mat_slice = np.array(mat[:2,:2]) # Notice the np.array command to create a new ar
print ("\nSliced matrix")
print(mat_slice)
Sliced matrix
[[11 12]
[21 22]]
In [167]: print ("\nChange the sliced matrix")
mat_slice[0,0] = 1000
print (mat_slice)
Change the sliced matrix
[[1000 12]
[ 21 22]]
In [168]: print("\nBut the original matrix? NO CHANGE this time:)")
print(mat)
But the original matrix? NO CHANGE this time:)
[[11 12 13]
[21 22 23]
[31 32 33]]
Universal Functions
In [169]: mat1 = np.array(ri(1,10,9)).reshape(3,3)
mat2 = np.array(ri(1,10,9)).reshape(3,3)
print("\n1st Matrix of random single-digit numbers\n----------------------------
print("\n2nd Matrix of random single-digit numbers\n----------------------------
1st Matrix of random single-digit numbers
----------------------------------------
[[6 9 9]
[2 2 7]
[8 7 3]]
2nd Matrix of random single-digit numbers
----------------------------------------
[[7 5 2]
[1 9 9]
[1 6 5]]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 18/50
2/28/2019 Numpy+Basics
In [170]: print("\nAddition\n------------------\n", mat1+mat2)
print("\nMultiplication\n------------------\n", mat1*mat2)
Addition
------------------
[[13 14 11]
[ 3 11 16]
[ 9 13 8]]
Multiplication
------------------
[[42 45 18]
[ 2 18 63]
[ 8 42 15]]
In [171]: print("\nDivision\n------------------\n", mat1/mat2)
print("\nLineaer combination: 3*A - 2*B\n-----------------------------\n", 3*mat1
Division
------------------
[[ 0.85714286 1.8 4.5 ]
[ 2. 0.22222222 0.77777778]
[ 8. 1.16666667 0.6 ]]
Lineaer combination: 3*A - 2*B
-----------------------------
[[ 4 17 23]
[ 4 -12 3]
[ 22 9 -1]]
In [172]: print("\nAddition of a scalar (100)\n-------------------------\n", 100+mat1)
Addition of a scalar (100)
-------------------------
[[106 109 109]
[102 102 107]
[108 107 103]]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 19/50
2/28/2019 Numpy+Basics
In [173]: print("\nExponentiation, matrix cubed here\n------------------------------------
print("\nExponentiation, sq-root using pow function\n---------------------------
Exponentiation, matrix cubed here
----------------------------------------
[[216 729 729]
[ 8 8 343]
[512 343 27]]
Exponentiation, sq-root using pow function
-------------------------------------------
[[ 2.44948974 3. 3. ]
[ 1.41421356 1.41421356 2.64575131]
[ 2.82842712 2.64575131 1.73205081]]
Broadcasting
In [174]: #NumPy operations are usually done on pairs of arrays on an element-by-element ba
#In the simplest case, the two arrays must have exactly the same shape.
#NumPy’s broadcasting rule relaxes this constraint when the arrays’ shapes meet c
#When operating on two arrays, NumPy compares their shapes element-wise. It start
#dimensions, and works its way forward. Two dimensions are compatible when
#they are equal, or one of them is 1
In [175]: start = np.zeros((4,3))
print(start)
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]]
In [176]: # create a rank 1 ndarray with 3 values
add_rows = np.array([1, 0, 2])
print(add_rows)
[1 0 2]
In [177]: y = start + add_rows # add to each row of 'start' using broadcasting
print(y)
[[ 1. 0. 2.]
[ 1. 0. 2.]
[ 1. 0. 2.]
[ 1. 0. 2.]]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 20/50
2/28/2019 Numpy+Basics
In [178]: # create an ndarray which is 4 x 1 to broadcast across columns
add_cols = np.array([[0,1,2,3]])
add_cols = add_cols.T
print(add_cols)
[[0]
[1]
[2]
[3]]
In [179]: # add to each column of 'start' using broadcasting
y = start + add_cols
print(y)
[[ 0. 0. 0.]
[ 1. 1. 1.]
[ 2. 2. 2.]
[ 3. 3. 3.]]
In [180]: # this will just broadcast in both dimensions
add_scalar = np.array([100])
print(start+add_scalar)
[[ 100. 100. 100.]
[ 100. 100. 100.]
[ 100. 100. 100.]
[ 100. 100. 100.]]
Array Math
In [181]: mat1 = np.array(ri(1,10,9)).reshape(3,3)
mat2 = np.array(ri(1,10,9)).reshape(3,3)
print("\n1st Matrix of random single-digit numbers\n----------------------------
print("\n2nd Matrix of random single-digit numbers\n----------------------------
1st Matrix of random single-digit numbers
----------------------------------------
[[7 7 3]
[4 1 9]
[5 9 7]]
2nd Matrix of random single-digit numbers
----------------------------------------
[[5 5 9]
[2 4 9]
[5 5 3]]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 21/50
2/28/2019 Numpy+Basics
In [182]: print("\nSq-root of 1st matrix using np\n------------------\n", np.sqrt(mat1))
Sq-root of 1st matrix using np
------------------
[[ 2.64575131 2.64575131 1.73205081]
[ 2. 1. 3. ]
[ 2.23606798 3. 2.64575131]]
In [183]: print("\nExponential power of 1st matrix using np\n",'-'*50,"\n", np.exp(mat1))
Exponential power of 1st matrix using np
--------------------------------------------------
[[ 1.09663316e+03 1.09663316e+03 2.00855369e+01]
[ 5.45981500e+01 2.71828183e+00 8.10308393e+03]
[ 1.48413159e+02 8.10308393e+03 1.09663316e+03]]
In [184]: print("\n10-base logarithm on 1st matrix using np\n",'-'*50,"\n", np.log10(mat1))
10-base logarithm on 1st matrix using np
--------------------------------------------------
[[ 0.84509804 0.84509804 0.47712125]
[ 0.60205999 0. 0.95424251]
[ 0.69897 0.95424251 0.84509804]]
In [185]: print("\nModulo reminder using np\n",'-'*50,"\n", np.fmod(mat1,mat2))
Modulo reminder using np
--------------------------------------------------
[[2 2 3]
[0 1 0]
[0 4 1]]
In [186]: print("\nCombination of functions by shwoing exponetial decay of a sine wave\n",
Combination of functions by shwoing exponetial decay of a sine wave
----------------------------------------------------------------------
In [187]: A = np.linspace(0,12*np.pi,1001)
In [188]: A
Out[188]: array([ 0. , 0.03769911, 0.07539822, ..., 37.62371362,
37.66141273, 37.69911184])
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 22/50
2/28/2019 Numpy+Basics
In [189]: import matplotlib.pyplot as plt
plt.scatter(x=A,y=100*np.exp(-A/10)*(np.sin(A)))
plt.title("Exponential decay of sine wave: exp(-x)*sin(x)")
plt.show()
In [3]: import numpy as np
In [2]: a = np.zeros((10, 2))
In [4]: # A transpose makes the array non-contiguous
In [5]: b = a.T
In [6]: c = b.view()
In [7]: c.shape = (20)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-7-7f6a843e0253> in <module>()
----> 1 c.shape = (20)
AttributeError: incompatible shape for a non-contiguous array
In [8]: #It is not always possible to change the shape of an array without copying the da
#If you want an error to be raised when the data is copied, you should assign the
#shape attribute of the array
In [10]: #The order keyword gives the index ordering both for fetching the values from a,
#into the output array
In [11]: a = np.arange(6).reshape((3, 2))
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 23/50
2/28/2019 Numpy+Basics
In [12]: a
Out[12]: array([[0, 1],
[2, 3],
[4, 5]])
In [13]: np.reshape(a, (2, 3))
Out[13]: array([[0, 1, 2],
[3, 4, 5]])
In [17]: #reshaping as first raveling the array
#then inserting the elements from the raveled array into the new array using the
In [14]: np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
Out[14]: array([[0, 1, 2],
[3, 4, 5]])
In [15]: np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
Out[15]: array([[0, 4, 3],
[2, 1, 5]])
In [16]: np.reshape(np.ravel(a, order='F'), (2, 3), order='F')
Out[16]: array([[0, 4, 3],
[2, 1, 5]])
In [18]: #examples
a = np.array([[1,2,3], [4,5,6]])
a
Out[18]: array([[1, 2, 3],
[4, 5, 6]])
In [19]: np.reshape(a, 6)
Out[19]: array([1, 2, 3, 4, 5, 6])
In [20]: np.reshape(a, 6, order='F')
Out[20]: array([1, 4, 2, 5, 3, 6])
In [21]: np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
Out[21]: array([[1, 2],
[3, 4],
[5, 6]])
In [22]: x = np.array([[1, 2, 3], [4, 5, 6]])
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 24/50
2/28/2019 Numpy+Basics
In [23]: print(np.ravel(x))
[1 2 3 4 5 6]
In [24]: print(x.reshape(-1))
[1 2 3 4 5 6]
In [25]: print(np.ravel(x, order='F'))
[1 4 2 5 3 6]
In [26]: #When order is ‘A’, it will preserve the array’s ‘C’ or ‘F’ ordering
In [27]: print(np.ravel(x.T))
[1 4 2 5 3 6]
In [28]: print(np.ravel(x.T, order='A'))
[1 2 3 4 5 6]
In [29]: #When order is ‘K’, it will preserve orderings that are neither ‘C’ nor ‘F’, but
In [30]: a = np.arange(3)[::-1]; a
Out[30]: array([2, 1, 0])
In [31]: a.ravel(order='C')
Out[31]: array([2, 1, 0])
In [32]: a.ravel(order='K')
Out[32]: array([2, 1, 0])
In [33]: a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a
Out[33]: array([[[ 0, 2, 4],
[ 1, 3, 5]],
[[ 6, 8, 10],
[ 7, 9, 11]]])
In [34]: a.ravel(order='C')
Out[34]: array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11])
In [35]: a.ravel(order='K')
Out[35]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 25/50
2/28/2019 Numpy+Basics
In [36]: #transpose:Permute the dimensions of an array.
#swapaxes:Interchange two axes of an array.
In [37]: x = np.zeros((3, 4, 5))
In [38]: np.moveaxis(x, 0, -1).shape
Out[38]: (4, 5, 3)
In [39]: np.moveaxis(x, -1, 0).shape
Out[39]: (5, 3, 4)
In [40]: np.transpose(x).shape
Out[40]: (5, 4, 3)
In [41]: np.swapaxes(x, 0, -1).shape
Out[41]: (5, 4, 3)
In [42]: np.moveaxis(x, [0, 1], [-1, -2]).shape
Out[42]: (5, 4, 3)
In [43]: np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape
Out[43]: (5, 4, 3)
In [44]: x = np.arange(4).reshape((2,2))
In [45]: x
Out[45]: array([[0, 1],
[2, 3]])
In [46]: np.transpose(x)
Out[46]: array([[0, 2],
[1, 3]])
In [47]: x
Out[47]: array([[0, 1],
[2, 3]])
In [48]: x = np.ones((1, 2, 3))
In [49]: np.transpose(x, (1, 0, 2)).shape
Out[49]: (2, 1, 3)
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 26/50
2/28/2019 Numpy+Basics
In [50]: #Convert inputs to arrays with at least one dimension.
In [51]: x = np.arange(9.0).reshape(3,3)
In [52]: np.atleast_1d(x)
Out[52]: array([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.]])
In [53]: np.atleast_1d(x) is x
Out[53]: True
In [54]: np.atleast_1d(1, [3, 4])
Out[54]: [array([1]), array([3, 4])]
In [55]: #View inputs as arrays with at least two dimensions.
In [56]: np.atleast_2d(3.0)
Out[56]: array([[ 3.]])
In [57]: x = np.arange(3.0)
In [58]: np.atleast_2d(x)
Out[58]: array([[ 0., 1., 2.]])
In [59]: np.atleast_2d(x).base is x
Out[59]: True
In [60]: np.atleast_2d(1, [1, 2], [[1, 2]])
Out[60]: [array([[1]]), array([[1, 2]]), array([[1, 2]])]
In [61]: #View inputs as arrays with at least three dimensions.
In [62]: x = np.arange(12.0).reshape(4,3)
In [63]: x
Out[63]: array([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.],
[ 9., 10., 11.]])
In [64]: np.atleast_3d(x).shape
Out[64]: (4, 3, 1)
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 27/50
2/28/2019 Numpy+Basics
In [65]: np.atleast_3d(x).base is x.base
Out[65]: True
In [66]: for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]):
... print(arr, arr.shape)
[[[1]
[2]]] (1, 2, 1)
[[[1]
[2]]] (1, 2, 1)
[[[1 2]]] (1, 1, 2)
In [67]: #Broadcast an array to a new shape, a very meaningful feature
In [106]: x = np.array([1, 2, 3])
In [107]: x
Out[107]: array([1, 2, 3])
In [108]: np.broadcast_to(x, (3, 3))
Out[108]: array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
In [103]: x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [104]: x
Out[104]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [105]: np.broadcast_to(x, (13, len(x)))
Out[105]: array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
In [109]: #Broadcast any number of arrays against each other
In [110]: x = np.array([[1,2,3]])
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 28/50
2/28/2019 Numpy+Basics
In [111]: x
Out[111]: array([[1, 2, 3]])
In [112]: y = np.array([[1],[2],[3]])
In [113]: y
Out[113]: array([[1],
[2],
[3]])
In [114]: np.broadcast_arrays(x, y)
Out[114]: [array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]), array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])]
In [115]: [np.array(a) for a in np.broadcast_arrays(x, y)]
Out[115]: [array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]), array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])]
In [116]: #Expand the shape of an array.
In [117]: x = np.array([1,2])
In [118]: x
Out[118]: array([1, 2])
In [119]: x.shape
Out[119]: (2,)
In [120]: y = np.expand_dims(x, axis=0)
In [121]: y
Out[121]: array([[1, 2]])
In [122]: y.shape
Out[122]: (1, 2)
In [123]: y = np.expand_dims(x, axis=1) # Equivalent to x[:,np.newaxis]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 29/50
2/28/2019 Numpy+Basics
In [124]: y
Out[124]: array([[1],
[2]])
In [125]: y.shape
Out[125]: (2, 1)
In [126]: np.newaxis is None
Out[126]: True
In [127]: #Remove single-dimensional entries from the shape of an array
In [128]: x = np.array([[[0], [1], [2]]])
In [129]: x
Out[129]: array([[[0],
[1],
[2]]])
In [130]: x.shape
Out[130]: (1, 3, 1)
In [131]: np.squeeze(x).shape
Out[131]: (3,)
In [132]: np.squeeze(x, axis=0).shape
Out[132]: (3, 1)
In [133]: np.squeeze(x, axis=1).shape
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-133-03d2df5273b7> in <module>()
----> 1 np.squeeze(x, axis=1).shape
~\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in squeeze(a, axis)
1196 try:
1197 # First try to use the new axis= parameter
-> 1198 return squeeze(axis=axis)
1199 except TypeError:
1200 # For backwards compatibility
ValueError: cannot select an axis to squeeze out which has size not equal to on
e
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 30/50
2/28/2019 Numpy+Basics
In [134]: np.squeeze(x, axis=2).shape
Out[134]: (1, 3)
In [135]: #Return an array converted to a float type
In [136]: np.asfarray([2, 3])
Out[136]: array([ 2., 3.])
In [137]: np.asfarray([2, 3], dtype='float')
Out[137]: array([ 2., 3.])
In [138]: np.asfarray([2, 3], dtype='int8')
Out[138]: array([ 2., 3.])
In [139]: #Join a sequence of arrays along an existing axis
In [140]: a = np.array([[1, 2], [3, 4]])
In [141]: a
Out[141]: array([[1, 2],
[3, 4]])
In [142]: b = np.array([[5, 6]])
In [143]: b
Out[143]: array([[5, 6]])
In [144]: np.concatenate((a, b), axis=0)
Out[144]: array([[1, 2],
[3, 4],
[5, 6]])
In [145]: np.concatenate((a, b.T), axis=1)
Out[145]: array([[1, 2, 5],
[3, 4, 6]])
In [146]: a = np.ma.arange(3)
In [147]: a
Out[147]: masked_array(data = [0 1 2],
mask = False,
fill_value = 999999)
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 31/50
2/28/2019 Numpy+Basics
In [148]: a[1] = np.ma.masked
In [149]: a
Out[149]: masked_array(data = [0 -- 2],
mask = [False True False],
fill_value = 999999)
In [150]: b = np.arange(2, 5)
In [151]: b
Out[151]: array([2, 3, 4])
In [152]: np.concatenate([a, b])
Out[152]: masked_array(data = [0 1 2 2 3 4],
mask = False,
fill_value = 999999)
In [153]: np.ma.concatenate([a, b])
Out[153]: masked_array(data = [0 -- 2 2 3 4],
mask = [False True False False False False],
fill_value = 999999)
In [154]: #Join a sequence of arrays along a new axis
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 32/50
2/28/2019 Numpy+Basics
In [155]: [np.random.randn(3, 4) for _ in range(10)]
Out[155]: [array([[ 0.14554751, -0.60835635, -0.02990939, -0.92486407],
[-0.11223634, 0.3997614 , 1.27141229, 0.63142596],
[-1.18113453, 1.0260625 , 0.79319697, -0.71844249]]),
array([[ 1.17925871, -2.53683011, -0.26032998, -0.51457485],
[ 0.58968602, 1.11727461, 0.76267513, -0.35389428],
[ 1.00501409, 0.95427581, -2.42096073, -1.16218212]]),
array([[ 0.12137246, 0.31806138, -0.15418759, -1.38144201],
[ 1.5455355 , -0.39448997, -0.67849026, 0.46412834],
[-1.0022328 , 0.98190205, 1.44751215, 0.04053402]]),
array([[-1.63235288, 1.10241399, -0.70186032, 0.47461136],
[-0.63219694, -1.43260066, 0.72321198, 0.4280372 ],
[ 0.04226522, 0.76104497, -1.83221429, -0.77756847]]),
array([[-1.59873979, 0.13900847, 1.67323645, -1.45090032],
[ 0.54050572, 0.09143111, 0.19695267, 0.71489649],
[ 0.24665063, 0.06607317, 1.40603306, -2.07246284]]),
array([[-0.49801507, -1.68675594, 0.5846229 , 0.33812499],
[-0.25488555, 0.04553139, -0.50742768, -1.25797967],
[-0.56872244, -1.05498515, -0.46106255, -0.75981975]]),
array([[-0.21802204, 1.15184542, -0.2106434 , 0.33915277],
[-0.69836483, 0.61824703, -1.44084449, 1.68961132],
[-0.0811926 , 0.89870109, -0.65740593, 0.41618152]]),
array([[-1.08662784, -0.26221083, -1.31976888, -2.85189365],
[-1.63203287, 0.58809261, -0.6563087 , -2.12895119],
[-0.84250433, -0.13057397, -0.83160789, -2.37144306]]),
array([[ 0.82061315, -0.43573079, 0.67479326, 0.23734688],
[-0.45538882, -0.00732324, 1.9832639 , -0.65820166],
[ 1.97858056, -0.24579971, -1.15198766, 0.31743116]]),
array([[-1.08712263, 0.92855908, 0.25690319, 0.07833283],
[-1.01495209, -0.6662424 , 0.67828769, 0.24434471],
[-1.74486622, 0.58048046, 0.47737193, -1.70413418]])]
In [156]: arrays = [np.random.randn(3, 4) for _ in range(10)]
In [157]: np.stack(arrays, axis=0).shape
Out[157]: (10, 3, 4)
In [158]: np.stack(arrays, axis=1).shape
Out[158]: (3, 10, 4)
In [159]: np.stack(arrays, axis=2).shape
Out[159]: (3, 4, 10)
In [160]: a = np.array([1, 2, 3])
In [161]: a
Out[161]: array([1, 2, 3])
In [162]: b = np.array([2, 3, 4])
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 33/50
2/28/2019 Numpy+Basics
In [163]: b
Out[163]: array([2, 3, 4])
In [164]: np.stack((a, b))
Out[164]: array([[1, 2, 3],
[2, 3, 4]])
In [165]: np.stack((a, b), axis=-1)
Out[165]: array([[1, 2],
[2, 3],
[3, 4]])
In [166]: np.column_stack((a,b)) #column stack
Out[166]: array([[1, 2],
[2, 3],
[3, 4]])
In [167]: np.dstack((a,b)) #depthwise stack
Out[167]: array([[[1, 2],
[2, 3],
[3, 4]]])
In [168]: np.hstack((a,b)) #horizontal stack
Out[168]: array([1, 2, 3, 2, 3, 4])
In [169]: np.vstack((a,b)) #vertical stacking
Out[169]: array([[1, 2, 3],
[2, 3, 4]])
In [170]: # split an array multiple sub-arrays
In [173]: x = np.arange(12.0)
In [174]: x
Out[174]: array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.,
11.])
In [175]: np.split(x, [3, 5, 6, 10])
Out[175]: [array([ 0., 1., 2.]),
array([ 3., 4.]),
array([ 5.]),
array([ 6., 7., 8., 9.]),
array([ 10., 11.])]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 34/50
2/28/2019 Numpy+Basics
In [176]: np.split(x, [3, 5, 8, 10, 12])
Out[176]: [array([ 0., 1., 2.]),
array([ 3., 4.]),
array([ 5., 6., 7.]),
array([ 8., 9.]),
array([ 10., 11.]),
array([], dtype=float64)]
In [177]: np.split(x,[5])
Out[177]: [array([ 0., 1., 2., 3., 4.]),
array([ 5., 6., 7., 8., 9., 10., 11.])]
In [178]: np.array_split(x,[5])
Out[178]: [array([ 0., 1., 2., 3., 4.]),
array([ 5., 6., 7., 8., 9., 10., 11.])]
In [179]: x = np.arange(16.0).reshape(2, 2, 4)
In [180]: x
Out[180]: array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]]])
In [181]: #multiple splits based on 3rd axis
In [182]: x = np.arange(16.0).reshape(2, 2, 4)
In [183]: x
Out[183]: array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]]])
In [184]: np.dsplit(x, 2)
Out[184]: [array([[[ 0., 1.],
[ 4., 5.]],
[[ 8., 9.],
[ 12., 13.]]]), array([[[ 2., 3.],
[ 6., 7.]],
[[ 10., 11.],
[ 14., 15.]]])]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 35/50
2/28/2019 Numpy+Basics
In [185]: np.dsplit(x, np.array([3, 6]))
Out[185]: [array([[[ 0., 1., 2.],
[ 4., 5., 6.]],
[[ 8., 9., 10.],
[ 12., 13., 14.]]]), array([[[ 3.],
[ 7.]],
[[ 11.],
[ 15.]]]), array([], shape=(2, 2, 0), dtype=float64)]
In [186]: np.hsplit(x, 2)
Out[186]: [array([[[ 0., 1., 2., 3.]],
[[ 8., 9., 10., 11.]]]), array([[[ 4., 5., 6., 7.]],
[[ 12., 13., 14., 15.]]])]
In [187]: np.hsplit(x, np.array([3, 6]))
Out[187]: [array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]]]),
array([], shape=(2, 0, 4), dtype=float64),
array([], shape=(2, 0, 4), dtype=float64)]
In [188]: np.hsplit(x, 2)
Out[188]: [array([[[ 0., 1., 2., 3.]],
[[ 8., 9., 10., 11.]]]), array([[[ 4., 5., 6., 7.]],
[[ 12., 13., 14., 15.]]])]
In [189]: np.vsplit(x, 2)
Out[189]: [array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]]]), array([[[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]]])]
In [190]: np.vsplit(x, np.array([3, 6]))
Out[190]: [array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]]]),
array([], shape=(0, 2, 4), dtype=float64),
array([], shape=(0, 2, 4), dtype=float64)]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 36/50
2/28/2019 Numpy+Basics
In [191]: np.tile(x, 2)
Out[191]: 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.],
[ 12., 13., 14., 15., 12., 13., 14., 15.]]])
In [192]: np.tile(x,(4,1))
Out[192]: array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]]])
In [193]: #repeating the arrays
In [194]: np.repeat(x, 2)
Out[194]: array([ 0., 0., 1., 1., 2., 2., 3., 3., 4., 4., 5.,
5., 6., 6., 7., 7., 8., 8., 9., 9., 10., 10.,
11., 11., 12., 12., 13., 13., 14., 14., 15., 15.])
In [195]: np.repeat(x, 3,axis=1)
Out[195]: array([[[ 0., 1., 2., 3.],
[ 0., 1., 2., 3.],
[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 4., 5., 6., 7.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[ 8., 9., 10., 11.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.],
[ 12., 13., 14., 15.],
[ 12., 13., 14., 15.]]])
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 37/50
2/28/2019 Numpy+Basics
In [196]: np.repeat(x, [1,2],axis=0)
Out[196]: array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]],
[[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]]])
In [197]: np.repeat(x, [1,2],axis=1)
Out[197]: array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.],
[ 12., 13., 14., 15.]]])
In [198]: np.delete(x, 1, 0)
Out[198]: array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]]])
In [199]: np.delete(x, np.s_[::2], 1)
Out[199]: array([[[ 4., 5., 6., 7.]],
[[ 12., 13., 14., 15.]]])
In [200]: np.delete(x, [1,3,5], None)
Out[200]: array([ 0., 2., 4., 6., 7., 8., 9., 10., 11., 12., 13.,
14., 15.])
In [201]: #insert values in an array
In [202]: np.insert(x, 1, 5)
Out[202]: array([ 0., 5., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
10., 11., 12., 13., 14., 15.])
In [203]: np.insert(x, 1, 5, axis=1)
Out[203]: array([[[ 0., 1., 2., 3.],
[ 5., 5., 5., 5.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[ 5., 5., 5., 5.],
[ 12., 13., 14., 15.]]])
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 38/50
2/28/2019 Numpy+Basics
In [204]: np.insert(x, [1], [[1],[2],[3]], axis=1)
Out[204]: array([[[ 0., 1., 2., 3.],
[ 1., 1., 1., 1.],
[ 2., 2., 2., 2.],
[ 3., 3., 3., 3.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[ 1., 1., 1., 1.],
[ 2., 2., 2., 2.],
[ 3., 3., 3., 3.],
[ 12., 13., 14., 15.]]])
In [209]: y = x.flatten()
In [210]: np.insert(y, [2, 2], [5, 6])
Out[210]: array([ 0., 1., 5., 6., 2., 3., 4., 5., 6., 7., 8.,
9., 10., 11., 12., 13., 14., 15.])
In [211]: np.insert(y, slice(2, 4), [5, 6])
Out[211]: array([ 0., 1., 5., 2., 6., 3., 4., 5., 6., 7., 8.,
9., 10., 11., 12., 13., 14., 15.])
In [213]: np.insert(y, [2, 2], [7.13, False])
Out[213]: array([ 0. , 1. , 7.13, 0. , 2. , 3. , 4. , 5. ,
6. , 7. , 8. , 9. , 10. , 11. , 12. , 13. ,
14. , 15. ])
In [214]: np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)
Out[214]: array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
In [219]: np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9])
Out[219]: array([1, 2, 3, 4, 5, 6, 7, 8, 9])
In [221]: np.resize(x,(2,4))
Out[221]: array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]])
In [222]: #getting the unique values from the numpy arrays
In [223]: np.unique([1, 1, 2, 2, 3, 3])
Out[223]: array([1, 2, 3])
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 39/50
2/28/2019 Numpy+Basics
In [224]: a = np.array([[1, 1], [2, 3]])
In [225]: a
Out[225]: array([[1, 1],
[2, 3]])
In [227]: np.unique(a)
Out[227]: array([1, 2, 3])
In [228]: a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
In [229]: a
Out[229]: array([[1, 0, 0],
[1, 0, 0],
[2, 3, 4]])
In [230]: np.unique(a, axis=0)
Out[230]: array([[1, 0, 0],
[2, 3, 4]])
In [237]: a = np.array(['a', 'b', 'b', 'c', 'a'])
In [238]: a
Out[238]: array(['a', 'b', 'b', 'c', 'a'],
dtype='<U1')
In [240]: u, indices = np.unique(a, return_index=True)
In [241]: u
Out[241]: array(['a', 'b', 'c'],
dtype='<U1')
In [242]: indices
Out[242]: array([0, 1, 3], dtype=int64)
In [243]: a[indices]
Out[243]: array(['a', 'b', 'c'],
dtype='<U1')
In [244]: a = np.array([1, 2, 6, 4, 2, 3, 2])
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 40/50
2/28/2019 Numpy+Basics
In [245]: a
Out[245]: array([1, 2, 6, 4, 2, 3, 2])
In [246]: u, indices = np.unique(a, return_inverse=True)
In [247]: u
Out[247]: array([1, 2, 3, 4, 6])
In [248]: indices
Out[248]: array([0, 1, 4, 3, 1, 2, 1], dtype=int64)
In [249]: u[indices]
Out[249]: array([1, 2, 6, 4, 2, 3, 2])
basic stats
In [252]: from numpy.random import randint as ri
mat1 = np.array(ri(1,10,9)).reshape(3,3)
mat2 = np.array(ri(1,10,9)).reshape(3,3)
print("\n1st Matrix of random single-digit numbers\n","-"*50,"\n",mat1)
print("\n2nd Matrix of random single-digit numbers\n","-"*50,"\n",mat2)
1st Matrix of random single-digit numbers
--------------------------------------------------
[[9 5 9]
[6 1 8]
[8 4 3]]
2nd Matrix of random single-digit numbers
--------------------------------------------------
[[7 3 2]
[1 4 2]
[9 8 8]]
In [253]: print("\nSum of all numbers in 1st matrix\n","-"*50,"\n",np.sum(mat1))
print("\nSum of all numbers in columns of 1st matrix\n","-"*50,"\n",np.sum(mat1,a
Sum of all numbers in 1st matrix
--------------------------------------------------
53
Sum of all numbers in columns of 1st matrix
--------------------------------------------------
[23 10 20]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 41/50
2/28/2019 Numpy+Basics
In [254]: print("\nSum of all numbers in rows of 1st matrix\n","-"*50,"\n",np.sum(mat1,axis
print("\nProduct of all numbers in rows of 1st matrix\n","-"*50,"\n",np.prod(mat1
Sum of all numbers in rows of 1st matrix
--------------------------------------------------
[23 15 15]
Product of all numbers in rows of 1st matrix
--------------------------------------------------
[405 48 96]
In [255]: print("\nProduct of all numbers in columns of 2nd matrix\n","-"*50,"\n",np.prod(m
print("\nMean of all numbers in 1st matrix\n","-"*50,"\n",np.mean(mat1))
Product of all numbers in columns of 2nd matrix
--------------------------------------------------
[63 96 32]
Mean of all numbers in 1st matrix
--------------------------------------------------
5.88888888889
In [256]: print("\nStandard deviation of all numbers in 1st matrix\n","-"*50,"\n",np.std(ma
Standard deviation of all numbers in 1st matrix
--------------------------------------------------
2.68512132747
In [257]: mat1 = np.array(ri(1,100,9)).reshape(3,3)
print("\nModified matrix of random numbers from 1 to 99\n","-"*50,"\n",mat1)
Modified matrix of random numbers from 1 to 99
--------------------------------------------------
[[41 34 94]
[79 20 23]
[61 4 90]]
In [258]: print("\nStandard deviation of all numbers in the modified matrix, a larger numbe
Standard deviation of all numbers in the modified matrix, a larger number
------------------------------------------------------------------------------
--
30.8728975393
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 42/50
2/28/2019 Numpy+Basics
In [259]: print("\nVariance of all numbers in the modified matrix, a larger number\n","-"*8
Variance of all numbers in the modified matrix, a larger number
------------------------------------------------------------------------------
--
953.135802469
In [260]: print("\nMedian of all numbers in the modified matrix\n","-"*60,"\n",np.median(ma
Median of all numbers in the modified matrix
------------------------------------------------------------
41.0
In [261]: mat2 = np.array(ri(1,100,50)).reshape(10,5)
In [262]: print("\nModified matrix of 50 random numbers from 1 to 99\n","-"*50,"\n",mat2)
Modified matrix of 50 random numbers from 1 to 99
--------------------------------------------------
[[41 40 44 13 41]
[39 67 47 34 99]
[17 13 3 58 92]
[14 38 35 29 89]
[ 5 97 84 10 41]
[22 49 9 18 15]
[61 17 6 68 69]
[75 52 55 92 31]
[60 71 75 43 11]
[29 5 11 27 77]]
In [263]: print("\nStandard deviation along the columns in the modified matrix\n","-"*60,"\
Standard deviation along the columns in the modified matrix
------------------------------------------------------------
[ 21.92281916 27.22296824 27.761304 25.00719896 31.02015474]
In [264]: mat1 = np.array(ri(1,100,20)).reshape(4,5)
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 43/50
2/28/2019 Numpy+Basics
In [265]: print("\nModified matrix of random numbers from 1 to 49\n","-"*50,"\n",mat1)
Modified matrix of random numbers from 1 to 49
--------------------------------------------------
[[37 72 74 57 7]
[93 64 9 80 58]
[28 13 16 87 55]
[56 14 38 21 69]]
In [266]: print("\nFlattened and sorted matrix (as vector)\n","-"*50,"\n",np.sort(mat1.resh
Flattened and sorted matrix (as vector)
--------------------------------------------------
[[ 7 9 13 14 16 21 28 37 38 55 56 57 58 64 69 72 74 80 87 93]]
In [267]: print("\n50th percentile of all numbers in the modified matrix\n","-"*60,"\n",np
50th percentile of all numbers in the modified matrix
------------------------------------------------------------
55.5
In [268]: print("\n90th percentile of all numbers in the modified matrix\n","-"*60,"\n",np
90th percentile of all numbers in the modified matrix
------------------------------------------------------------
80.7
Correlation
In [269]: A = ri(1,5,20) # 20 random integeres from a small range (1-10)
B = 2*A+5*np.random.randn(20) # B is twice that of A plus some random noise
print("\nB is twice that of A plus some random noise")
B is twice that of A plus some random noise
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 44/50
2/28/2019 Numpy+Basics
In [273]: import matplotlib.pyplot as plt
%matplotlib inline
plt.scatter(A,B) # Scatter plot of B
plt.title("Scatter plot of A vs. B, expect a small positive correlation")
plt.show()
In [274]: print(np.corrcoef(A,B)) # Correleation coefficient matrix between A and B
[[ 1. 0.68171563]
[ 0.68171563 1. ]]
In [275]: A = ri(1,50,20) # 20 random integeres from a larger range (1-50)
B = 100-2*A+10*np.random.randn(20) # B is 100 minus twice that of A plus some ran
print("\nB is 100 minus twice that of A plus some random noise")
B is 100 minus twice that of A plus some random noise
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 45/50
2/28/2019 Numpy+Basics
In [276]: plt.scatter(A,B) # Scatter plot of B
plt.title("Scatter plot of A vs. B, expect a large negative correlation")
plt.show()
In [277]: print("")
print(np.corrcoef(A,B)) # Correleation coefficient matrix between A and B
[[ 1. -0.98606912]
[-0.98606912 1. ]]
Linear Algebra Using Numpy
In [278]: A = np.arange(1,10).reshape(3,3)
B = ri(1,10,9).reshape(3,3)
print("\n1st Matrix of 1-9 single-digit numbers (A)\n","-"*50,"\n",A)
1st Matrix of 1-9 single-digit numbers (A)
--------------------------------------------------
[[1 2 3]
[4 5 6]
[7 8 9]]
In [279]: print("\n2nd Matrix of random single-digit numbers (B)\n","-"*50,"\n",B)
2nd Matrix of random single-digit numbers (B)
--------------------------------------------------
[[6 4 7]
[7 1 4]
[2 6 5]]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 46/50
2/28/2019 Numpy+Basics
In [280]: print("\nDot product of A and B (for 2D arrays it is equivalent to matrix multipl
Dot product of A and B (for 2D arrays it is equivalent to matrix multiplicatio
n)
------------------------------------------------------------------------------
--
[[ 26 24 30]
[ 71 57 78]
[116 90 126]]
In [281]: A = np.arange(1,6)
B = ri(1,10,5)
In [282]: print("\n1st Vector of 1-5 numbers (A)\n","-"*50,"\n",A)
1st Vector of 1-5 numbers (A)
--------------------------------------------------
[1 2 3 4 5]
In [283]: print("\n2nd Vector of 5 random single-digit numbers (B)\n","-"*50,"\n",B)
2nd Vector of 5 random single-digit numbers (B)
--------------------------------------------------
[9 3 1 5 4]
In [284]: print("\nInner product of vectors A and B \n","-"*50,"\n",np.inner(A,B), "(sum of
Inner product of vectors A and B
--------------------------------------------------
58 (sum of all pairwise elements)
In [285]: print("\nOuter product of vectors A and B \n","-"*50,"\n",np.outer(A,B))
Outer product of vectors A and B
--------------------------------------------------
[[ 9 3 1 5 4]
[18 6 2 10 8]
[27 9 3 15 12]
[36 12 4 20 16]
[45 15 5 25 20]]
In [286]: #matrix transpose and matrix inverse
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 47/50
2/28/2019 Numpy+Basics
In [287]: A = ri(1,10,9).reshape(3,3)
In [288]: A
Out[288]: array([[4, 5, 6],
[7, 2, 3],
[8, 5, 3]])
In [289]: print("\n3x3 Matrix of random single-digit numbers\n","-"*50,"\n",A)
3x3 Matrix of random single-digit numbers
--------------------------------------------------
[[4 5 6]
[7 2 3]
[8 5 3]]
In [290]: print("\nMatrix transpose\n","-"*50,"\n",np.transpose(A))
Matrix transpose
--------------------------------------------------
[[4 7 8]
[5 2 5]
[6 3 3]]
In [291]: B = ri(1,10,6).reshape(3,2)
In [292]: B
Out[292]: array([[4, 5],
[4, 4],
[4, 2]])
In [293]: print("\n3x2 Matrix of random single-digit numbers\n","-"*50,"\n",B)
3x2 Matrix of random single-digit numbers
--------------------------------------------------
[[4 5]
[4 4]
[4 2]]
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 48/50
2/28/2019 Numpy+Basics
In [294]: print("\n2x3 Matrix transpose\n","-"*50,"\n",np.transpose(B))
2x3 Matrix transpose
--------------------------------------------------
[[4 4 4]
[5 4 2]]
In [295]: print("\nMatrix multiplication of B and B-transpose\n","-"*50,"\n",np.dot(B, np.t
Matrix multiplication of B and B-transpose
--------------------------------------------------
[[41 36 26]
[36 32 24]
[26 24 20]]
In [296]: #finding trace of a matrix
In [297]: A = ri(1,10,16).reshape(4,4)
In [298]: A
Out[298]: array([[7, 9, 3, 7],
[9, 3, 7, 4],
[1, 9, 2, 3],
[9, 6, 2, 6]])
In [299]: print("\n4x4 Matrix of random single-digit numbers\n","-"*50,"\n",A)
4x4 Matrix of random single-digit numbers
--------------------------------------------------
[[7 9 3 7]
[9 3 7 4]
[1 9 2 3]
[9 6 2 6]]
In [300]: print("\nMatrix trace\n","-"*50,"\n",np.trace(A))
Matrix trace
--------------------------------------------------
18
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 49/50
2/28/2019 Numpy+Basics
In [301]: print("\nMatrix trace with ofset +1 (upper triangle)\n","-"*50,"\n",np.trace(A,of
Matrix trace with ofset +1 (upper triangle)
--------------------------------------------------
19
In [302]: print("\nMatrix trace with ofset -1 (lower triangle)\n","-"*50,"\n",np.trace(A,of
Matrix trace with ofset -1 (lower triangle)
--------------------------------------------------
20
In [ ]:
http://localhost:8888/notebooks/Numpy%2BBasics.ipynb 50/50