【Python】Numpy Learning Notes

Brief Introduction

Brief Introduction to numpy

NumPy (Numerical Python) is an open source Python library that’s used in almost every field of science and engineering. It’s the universal standard for working with numerical data in Python, and it’s at the core of the scientific Python and PyData ecosystems. NumPy users include everyone from beginning coders to experienced researchers doing state-of-the-art scientific and industrial research and development. The NumPy API is used extensively in Pandas, SciPy,Matplotlib, scikit-learn, scikit-image and most other data science and scientific Python packages.
The NumPy library contains multidimensional array and matrix data structures (you’ll find more information about this in later sections). It provides ndarray, a homogeneous n-dimensional array object, with methods to efficiently operate on it. NumPy can be used to perform a wide variety of mathematical operations on arrays. It adds powerful data structures to Python that guarantee efficient calculations with arrays and matrices and it supplies an enormous library of high-level mathematical functions that operate on these arrays and matrices.

What is an array in Numpy?

An array is a central data structure of the NumPy library. An array is a grid of values and it contains information about the raw data, how to locate an element, and how to interpret an element. It has a grid of elements that can be indexed in various ways. The elements are all of the same type, referred to as the array dtype.
An array can be indexed by a tuple of nonnegative integers, by booleans, by another array, or by integers. The rank of the array is the number of dimensions. The shape of the array is a tuple of integers giving the size of the array along each dimension.

You might occasionally hear an array referred to as a “ndarray,” which is shorthand for “N-dimensional array.” An N-dimensional array is simply an array with any number of dimensions. You might also hear 1-D, or one-dimensional array, 2-D, or two-dimensional array, and so on. The NumPy ndarray class is used to represent both matrices and vectors. A vector is an array with a single dimension (there’s no difference between row and column vectors), while a matrix refers to an array with two dimensions. For 3-D or higher dimensional arrays, the term tensor is also commonly used.

Differences between a Python list & Numpy array

NumPy gives you an enormous range of fast and efficient ways of creating arrays and manipulating numerical data inside them. While a Python list can contain different data types within a single list, all of the elements in a NumPy array should be homogeneous. The mathematical operations that are meant to be performed on arrays would be extremely inefficient if the arrays weren’t homogeneous.
NumPy arrays are faster and more compact than Python lists. An array consumes less memory and is convenient to use. NumPy uses much less memory to store data and it provides a mechanism of specifying the data types. This allows the code to be optimized even further.

Some basic attributes of Numpy array

import numpy as np
a = np.arange(1,13).reshape(2,6)
print('Original Matrix:\n{}'.format(a))

print('\ntype(a):\n{}'.format(type(a)))       #return the type of a -> 'numpy.ndarray'
print('\na.ndim:\n{}'.format(a.ndim))         #return a number of axes (dimensions) of the array
print('\na.shape:\n{}'.format(a.shape))       #return a tuple of integers indicating the size of the array in each dimension
print('\na.size:\n{}'.format(a.size))         #return the total number of elements of the array
print('\na.dtype:\n{}'.format(a.dtype))       #return the type of elements of the array
print('\na.itemsize:\n{}'.format(a.itemsize)) #return the the size in bytes of each element of the array

Original Matrix:
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]

type(a):
<class ‘numpy.ndarray’>

a.ndim:
2

a.shape:
(2, 6)

a.size:
12

a.dtype:
int32

a.itemsize:
4

Arrays Creation

array( )

import numpy as np    
a = np.array([1,2,3,4])  #array() helps to transform a Python list to Numpy arrary
b = np.array([[2.1,3.4],[3.7,4.2]])
c = np.array([1,2,3],dtype=complex) #'dtype' can specify the type of the elements
print('An array with int type elements:\n{}'.format(a))
print('\nAn array with float type elements:\n{}'.format(b))
print('\nAn array with complex type elements:\n{}'.format(c))

An array with int type elements:
[1 2 3 4]

An array with float type elements:
[[2.1 3.4]
[3.7 4.2]]

An array with complex type elements:
[1.+0.j 2.+0.j 3.+0.j]

Typical errors caused by array( )

parameters error

a = np.array(1,2,3,4)   #Wrong Version
a = np.array([1,2,3,4]) #Right Version

b = np.array([1.6,13.4],[2.1,3.6])   #Wrong Version
b = np.array([[1.6,13.4],[2.1,3.6]]) #Right Version
   TypeError                                 Traceback (most recent call last)
   ~\AppData\Local\Temp/ipykernel_15416/3711612825.py in <module>
    ----> 1 a = np.array(1,2,3,4)   #Wrong Version
          2 a = np.array([1,2,3,4]) #Right Version
          3 
          4 b = np.array([1.6,13.4],[2.1,3.6])   #Wrong Version
          5 b = np.array([[1.6,13.4],[2.1,3.6]]) #Correct Version
          
   TypeError: array() takes from 1 to 2 positional arguments but 4 were given

1-D array is different from 1-D vector

#1-D array is different from 1-D vector => reshape()is inevitable in a vector creation
a = np.array([1,2,3,4])
print('a:\n{}'.format(a)) 
b = np.array([1,2,3,4])
print('b:\n{}'.format(b)) 
print('a.ndim: {}'.format(a.ndim)) #Note that a is not a vector(1-D array is different from 1-D vector)
print('b.ndim: {}'.format(b.ndim)) #Note that b is not a vector(1-D array is different from 1-D vector)
print('a*b:\n{}'.format(a@b))

a = np.array([1,2,3,4]).reshape(1,4)
print('\na:\n{}'.format(a)) 
b = np.array([1,2,3,4]).reshape(1,4)
print('b:\n{}'.format(b)) 
print('a.ndim: {}'.format(a.ndim)) 
print('b.ndim: {}'.format(b.ndim)) 
print('a*b:\n{}'.format(a@b.T))    #Different product result 

a:
[1 2 3 4]
b:
[1 2 3 4]
a.ndim: 1
b.ndim: 1
a*b:
30

a:
[[1 2 3 4]]
b:
[[1 2 3 4]]
a.ndim: 2
b.ndim: 2
a*b:
[[30]]

arange( ) & reshape( )

a = np.arange(10,30,5)                #arange(start,end,step) => [start,end)
print('An array begins at 10 & ends up at 25 by the step of 5:\n{}'.format(a))
b = np.arange(10,40,5).reshape(2,3)   #reshape((size of 0 axis,size of 1 axis))
print('\nAn array begins at 10 & ends up at 35 by the step of 5 & reshape into a 2*3 Matrix:\n{}'.format(b))
c = np.arange(15).reshape(3,5)
print('\nAn array begins at 0 & ends up at 14 by the step of 1 & reshape into a 3*5 Matrix:\n{}'.format(c))

An array begins at 10 & ends up at 25 by the step of 5:
[10 15 20 25]

An array begins at 10 & ends up at 35 by the step of 5 & reshape into a 2*3 Matrix:
[[10 15 20]
[25 30 35]]

An array begins at 0 & ends up at 14 by the step of 1 & reshape into a 3*5 Matrix:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]

linspace( )

#linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
a = np.linspace(0,10)         #Returns num(default value = 50) evenly spaced samples, calculated over the interval [start, stop].
print('Without assigning "num":\n{}'.format(a))
b = np.linspace(0, 10, num=5) 
print("\nAssign 'num' to 5:\n{}".format(b))

Without assigning “num”:
[ 0. 0.20408163 0.40816327 0.6122449 0.81632653 1.02040816
1.2244898 1.42857143 1.63265306 1.83673469 2.04081633 2.24489796
2.44897959 2.65306122 2.85714286 3.06122449 3.26530612 3.46938776
3.67346939 3.87755102 4.08163265 4.28571429 4.48979592 4.69387755
4.89795918 5.10204082 5.30612245 5.51020408 5.71428571 5.91836735
6.12244898 6.32653061 6.53061224 6.73469388 6.93877551 7.14285714
7.34693878 7.55102041 7.75510204 7.95918367 8.16326531 8.36734694
8.57142857 8.7755102 8.97959184 9.18367347 9.3877551 9.59183673
9.79591837 10. ]

Assign ‘num’ to 5:
[ 0. 2.5 5. 7.5 10. ]

random.randint( )

a = np.random.randint(1,10,(2,5))  #random.randint(start,end,(size of 0 axis,size of 1 axis))
print('An 2*5 random array:\n{}'.format(a))
b = np.random.randint(1,5,(4,2))   #random.randint creates a matrix filled with random value between [start,end)
print('\nAn 4*2 random array:\n{}'.format(a))

An 2*5 random array:
[[2 7 8 7 5]
[9 4 8 8 9]]

An 4*2 random array:
[[2 7 8 7 5]
[9 4 8 8 9]]

zeros( ) & ones( )

a = np.zeros((2,2))   #zeros(tuple)
print('An array filled with 0's:\n{}'.format(a))
b = np.ones((2,5))    #ones(tuple)
print('\nAn array filled with 1's:\n{}'.format(b))

An array filled with 0’s:
[[0. 0.]
[0. 0.]]

An array filled with 1’s:
[[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]]

eye( )

a = np.eye(5)  #eye(size) => a identity matrix(normally square matrix)
print('An 5*5 identity array:\n{}'.format(a))

An 5*5 identity array:
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]

Shape Manipulation

reshape( ) & ravel( ) & a.T & resize( )

a = np.random.randint(1,10,(3,4))
print('Original Matrix:\n{}'.format(a))
#a.shape
print('\na.shape:\n{}'.format(a.shape))

#a.ravel()
print('\na.ravel():\n{}'.format(a.ravel()))  #a.ravel() does not change the original matrix
print('\nCurrent a:\n{}'.format(a))

#a.reshape()
print('\na.reshape(4,3):\n{}'.format(a.reshape(4,3)))  #a.reshape() does not change the original matrix
print('\nCurrent a:\n{}'.format(a))
#If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated
print('\na.reshape(4,-1):\n{}'.format(a.reshape(4,-1))) 
print('\nCurrent a:\n{}'.format(a))

#a.T or a.transpose()
print('\na.T:\n{}'.format(a.T))  #a.T() does not change the original matrix
print('\nCurrent a:\n{}'.format(a))

#a.resize() => to resize the shape of a
print('\na.resize():\n{}'.format(a.resize((2,6))))  #a.resize() does change the original matrix
print('\nCurrent a:\n{}'.format(a))

Original Matrix:
[[2 5 6 7]
[3 5 1 3]
[7 3 2 3]]

a.shape:
(3, 4)

a.ravel():
[2 5 6 7 3 5 1 3 7 3 2 3]

Current a:
[[2 5 6 7]
[3 5 1 3]
[7 3 2 3]]

a.reshape(4,3):
[[2 5 6]
[7 3 5]
[1 3 7]
[3 2 3]]

Current a:
[[2 5 6 7]
[3 5 1 3]
[7 3 2 3]]

a.reshape(4,-1):
[[2 5 6]
[7 3 5]
[1 3 7]
[3 2 3]]

Current a:
[[2 5 6 7]
[3 5 1 3]
[7 3 2 3]]

a.T:
[[2 3 7]
[5 5 3]
[6 1 2]
[7 3 3]]

Current a:
[[2 5 6 7]
[3 5 1 3]
[7 3 2 3]]

a.resize():
None

Current a:
[[2 5 6 7 3 5]
[1 3 7 3 2 3]]

vstack( ) & hstack

A= np.arange(1,9).reshape(2,4)
print('Original Matrix A:\n{}'.format(A))

B= np.arange(5,13).reshape(2,4)
print('\nOriginal Matrix B:\n{}'.format(B))

print('\nvstack((A,B)):\n{}'.format(np.vstack((A,B))))

print('\nhstack((A,B)):\n{}'.format(np.hstack((A,B))))

Original Matrix A:
[[1 2 3 4]
[5 6 7 8]]

Original Matrix B:
[[ 5 6 7 8]
[ 9 10 11 12]]

vstack((A,B)):
[[ 1 2 3 4]
[ 5 6 7 8]
[ 5 6 7 8]
[ 9 10 11 12]]

hstack((A,B)):
[[ 1 2 3 4 5 6 7 8]
[ 5 6 7 8 9 10 11 12]]

concatenate( )

a = np.arange(1,13).reshape(4,3)
print('Original Matrix a:\n{}'.format(a))

b = np.ones((4,1),dtype = int)
print('\nOriginal Matrix b:\n{}'.format(b))

#numpy.concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting="same_kind")
print('\nConcatenated Matrix:\n{}'.format(np.concatenate((b,a),axis=1)))
print('Current Matrix a:\n{}'.format(a))
print('Current Matrix b:\n{}'.format(b))

Original Matrix a:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]

Original Matrix b:
[[1]
[1]
[1]
[1]]

Concatenated Matrix:
[[ 1 1 2 3]
[ 1 4 5 6]
[ 1 7 8 9]
[ 1 10 11 12]]
Current Matrix a:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Current Matrix b:
[[1]
[1]
[1]
[1]]

Splitting one array into several smaller ones

a = np.arange(1,21).reshape(2,10)
print('Original Matrix:\n{}'.format(a))

print('\nnp.hsplit(a,5):\n{}'.format(np.hsplit(a,5))) #split a into 5 arrays with the same size
print('Current a:\n{}'.format(a))

print('\nnp.hsplit(a,(2,5)):\n{}'.format(np.hsplit(a,(2,5))))  #split a into 3 arrays,the column index of middle one is col2 to col5

Original Matrix:
[[ 1 2 3 4 5 6 7 8 9 10]
[11 12 13 14 15 16 17 18 19 20]]

np.hsplit(a,5):
[array([[ 1, 2],
[11, 12]]), array([[ 3, 4],
[13, 14]]), array([[ 5, 6],
[15, 16]]), array([[ 7, 8],
[17, 18]]), array([[ 9, 10],
[19, 20]])]
Current a:
[[ 1 2 3 4 5 6 7 8 9 10]
[11 12 13 14 15 16 17 18 19 20]]

np.hsplit(a,(2,5)):
[array([[ 1, 2],
[11, 12]]), array([[ 3, 4, 5],
[13, 14, 15]]), array([[ 6, 7, 8, 9, 10],
[16, 17, 18, 19, 20]])]

Basic Operations

Print Arrays to the Screen

a = np.arange(6) 
print('1-D:\n{}\n'.format(a))

b= np.arange(12).reshape((3,4))
print('2-D:\n{}\n'.format(b))

c = np.arange(24).reshape(2,2,3,2)
print('3-D:\n{}\n'.format(c))

a = np.arange(10000)
print(a)

b = np.arange(10000).reshape(100,100)
print(b)

1-D:
[0 1 2 3 4 5]

2-D:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]

3-D:
[[[[ 0 1]
[ 2 3]
[ 4 5]]

[[ 6 7]
[ 8 9]
[10 11]]]

[[[12 13]
[14 15]
[16 17]]

[[18 19]
[20 21]
[22 23]]]]

[ 0 1 2 … 9997 9998 9999]

[[ 0 1 2 … 97 98 99]
[ 100 101 102 … 197 198 199]
[ 200 201 202 … 297 298 299]

[9700 9701 9702 … 9797 9798 9799]
[9800 9801 9802 … 9897 9898 9899]
[9900 9901 9902 … 9997 9998 9999]]

sort

a = np.random.randint(1,11,(2,5))
print('Original Matrix:\n{}\n'.format(a))

#numpy.sort(a, axis=-1, kind=None, order=None)
#axis = {-1,0,1,None}
#kind={'quicksort','mergesort','heapsort','stable'}

#sort along the row with axis=-1
print('np.sort(a):\n{}'.format(np.sort(a))) #sort along the row,default value of axis is -1
print('Current a:\n{}\n'.format(a))         #The result indicates that np.sort() will not mofify the original matrix

#sort along the column with axis=0
print('np.sort(a,axis=0):\n{}'.format(np.sort(a,axis=0))) 
print('np.sort(a,axis=0)[::-1,:]:\n{}'.format(np.sort(a,axis=0)[::-1,:])) #right way to reverse =>Select all the column & reverse all the row
print('np.sort(a,axis=0)[:,::-1]:\n{}'.format(np.sort(a,axis=0)[:,::-1])) #wrong way to reverse
print('Pay attention to the reversing code!Try to comprehend it with the help of the comments!')
print('Current a:\n{}\n'.format(a))

#sort along the row with axis=1(same with axis=-1)
print('np.sort(a,axis=1):\n{}'.format(np.sort(a,axis=1))) 
print('np.sort(a,axis=1)[:,::-1]:\n{}'.format(np.sort(a,axis=1)[:,::-1])) #right way to reverse =>Select all the row & reverse all the colunm
print('np.sort(a,axis=1)[::-1,:]:\n{}'.format(np.sort(a,axis=1)[::-1,:])) #wrong way to reverse
print('Pay attention to the reversing code!Try to comprehend it with the help of the comments!')
print('Current a:\n{}\n'.format(a))

#sort the flattened array with axis=None
print('np.sort(a,axis=None):\n{}'.format(np.sort(a,axis=None))) 
print('np.sort(a,axis=None)[::-1]:\n{}'.format(np.sort(a,axis=None)[::-1])) #reverse the sorted the flattened array
print('Current a:\n{}\n'.format(a))

Original Matrix:
[[10 2 7 4 3]
[ 7 8 2 1 8]]

np.sort(a):
[[ 2 3 4 7 10]
[ 1 2 7 8 8]]
Current a:
[[10 2 7 4 3]
[ 7 8 2 1 8]]

np.sort(a,axis=0):
[[ 7 2 2 1 3]
[10 8 7 4 8]]
np.sort(a,axis=0)[::-1,:]:
[[10 8 7 4 8]
[ 7 2 2 1 3]]
np.sort(a,axis=0)[:,::-1]:
[[ 3 1 2 2 7]
[ 8 4 7 8 10]]
Pay attention to the reversing code!Try to comprehend it with the help of the comments!
Current a:
[[10 2 7 4 3]
[ 7 8 2 1 8]]

np.sort(a,axis=1):
[[ 2 3 4 7 10]
[ 1 2 7 8 8]]
np.sort(a,axis=1)[:,::-1]:
[[10 7 4 3 2]
[ 8 8 7 2 1]]
np.sort(a,axis=1)[::-1,:]:
[[ 1 2 7 8 8]
[ 2 3 4 7 10]]
Pay attention to the reversing code!Try to comprehend it with the help of the comments!
Current a:
[[10 2 7 4 3]
[ 7 8 2 1 8]]

np.sort(a,axis=None):
[ 1 2 2 3 4 7 7 8 8 10]
np.sort(a,axis=None)[::-1]:
[10 8 8 7 7 4 3 2 2 1]
Current a:
[[10 2 7 4 3]
[ 7 8 2 1 8]]

Reverse

a = np.arange(6).reshape(1,6)
print('Original Matrix a:\n{}\n'.format(a))
print('Reversed Matrix a:\n{}\n'.format(np.flip(a)))  #np.flip(a)
print('Current Matrix a:\n{}\n'.format(a))            #flip will not modify the original matrix

b = np.arange(12).reshape(2,6)
print('Original Matrix b:\n{}\n'.format(b))
print('Reversed Matrix b:\n{}\n'.format(np.flip(b)))  #np.flip(a)
print('Reversed Matrix b(axis=0):\n{}\n'.format(np.flip(b,axis=0))) 
print('Reversed Matrix b(axis=1):\n{}\n'.format(np.flip(b,axis=1))) 
print('Current Matrix b:\n{}\n'.format(b))            #flip will not modify the original matrix

Original Matrix a:
[[0 1 2 3 4 5]]

Reversed Matrix a:
[[5 4 3 2 1 0]]

Current Matrix a:
[[0 1 2 3 4 5]]

Original Matrix b:
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]]

Reversed Matrix b:
[[11 10 9 8 7 6]
[ 5 4 3 2 1 0]]

Reversed Matrix b(axis=0):
[[ 6 7 8 9 10 11]
[ 0 1 2 3 4 5]]

Reversed Matrix b(axis=1):
[[ 5 4 3 2 1 0]
[11 10 9 8 7 6]]

Current Matrix b:
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]]

Addition & Substraction & Scalar Multiplication & Logic Judgment

a = np.arange(6)
b = np.arange(2,8)
print('Original Matrix:\n{}\n{}\n'.format(a,b))
print('Addition:\n{}\n'.format(a+b))
print('Substraction:\n{}\n'.format(a-b))
print('Scalar Multiplication:\n{}'.format(a*10))
print(a**3)
print('\nLogic Judgment:\n{}'.format(a<3))

Original Matrix:
[0 1 2 3 4 5]
[2 3 4 5 6 7]

Addition:
[ 2 4 6 8 10 12]

Substraction:
[-2 -2 -2 -2 -2 -2]

Scalar Multiplication:
[ 0 10 20 30 40 50]
[ 0 1 8 27 64 125]

Logic Judgment:
[ True True True False False False]

Matrix Multiplication

a = np.arange(1,11).reshape(5,2)
b = np.arange(5,15).reshape(2,5)
print('Original Matrix A:\n{}'.format(a))
print('Original Matrix B:\n{}'.format(b))
print('\nA*B:')
print(a@b)               #a@b is equal to a.dot(b)
print(a.dot(b))

Original Matrix A:
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]]
Original Matrix B:
[[ 5 6 7 8 9]
[10 11 12 13 14]]

A*B:
[[ 25 28 31 34 37]
[ 55 62 69 76 83]
[ 85 96 107 118 129]
[115 130 145 160 175]
[145 164 183 202 221]]
[[ 25 28 31 34 37]
[ 55 62 69 76 83]
[ 85 96 107 118 129]
[115 130 145 160 175]
[145 164 183 202 221]]

Sum( )& Cumulative Sum( )

a = np.random.randint(5,10,(3,5))
print('Original Matrix:\n{}'.format(a))

print('\nSum:')
print(a.sum())
print(a.sum(axis=0))    #sum of each column
print(a.sum(axis=1))    #sum of each row

print('\nCumulative Sum:')
print(a.cumsum(axis=0)) #cumulative sum along each column
print(a.cumsum(axis=1)) #cumulative sum along each row

Original Matrix:
[[5 7 6 9 5]
[6 9 5 8 9]
[7 6 8 9 8]]

Sum:
107
[18 22 19 26 22]
[32 37 38]

Cumulative Sum:
[[ 5 7 6 9 5]
[11 16 11 17 14]
[18 22 19 26 22]]
[[ 5 12 18 27 32]
[ 6 15 20 28 37]
[ 7 13 21 30 38]]

Max( ) & Min( )

a = np.random.randint(10,20,(4,2))
print('Original Matrix:\n{}'.format(a))

print('\nMax:')
print(a.max())
print(a.max(axis=0))    #max of each column
print(a.max(axis=1))    #max of each row

print('\nMin:')
print(a.min())
print(a.min(axis=0))    #min of each column
print(a.max(axis=1))    #min of each row

Original Matrix:
[[16 18]
[14 14]
[11 18]
[10 16]]

Max:
18
[16 18]
[18 14 18 16]

Min:
10
[10 14]
[18 14 18 16]

exp( ) & sqrt( ) & add( )

import numpy as np
a = np.arange(1,11).reshape(2,5)
b = np.arange(1,11).reshape(2,5)
print('Original Matrix:\n{}'.format(a))
print('\nExp():\n{}'.format(np.exp(a)))
print('\nSqrt():\n{}'.format(np.sqrt(a)))
print('\nAdd():\n{}'.format(np.add(a,b)))

Original Matrix:
[[ 1 2 3 4 5]
[ 6 7 8 9 10]]

Exp():
[[2.71828183e+00 7.38905610e+00 2.00855369e+01 5.45981500e+01
1.48413159e+02]
[4.03428793e+02 1.09663316e+03 2.98095799e+03 8.10308393e+03
2.20264658e+04]]

Sqrt():
[[1. 1.41421356 1.73205081 2. 2.23606798]
[2.44948974 2.64575131 2.82842712 3. 3.16227766]]

Add():
[[ 2 4 6 8 10]
[12 14 16 18 20]]

Indexing & Slicing & Iterating

1-D Array

a = np.arange(10)**3
print('Original Matrix:\n{}'.format(a))

print('\na[2]:\n{}'.format(a[2]))        #Indexing
print('\na[:6:2]:\n{}'.format(a[:6:2]))  #Slicing      a[start:end:step]

a[4::2] = 1000
print('\nModified Matrix:\n{}'.format(a))

print('\nReversed Matrix:\n{}'.format(a[::-1]))

Original Matrix:
[ 0 1 8 27 64 125 216 343 512 729]

a[2]:
8

a[:6:2]:
[ 0 8 64]

Modified Matrix:
[ 0 1 8 27 1000 125 1000 343 1000 729]

Reversed Matrix:
[ 729 1000 343 1000 125 1000 27 8 1 0]

n-D Arrays

a = np.random.randint(1,20,(4,5))
print('Original Matrix:\n{}'.format(a))

print('\na[3,4]:\n{}'.format(a[3,4]))

print('\na[1:3,2:]:\n{}'.format(a[1:3,2:]))

print('\na[:,0]:\n{}'.format(a[:,0]))

print('\na[-1]:\n{}'.format(a[-1]))   # the last row. Equivalent to a[-1, :]

print('\nIterating:')
for row in a:
    print(row)
    
for element in a.flat:   #a.flat
    print(element)

Original Matrix:
[[19 4 18 6 5]
[ 4 16 18 4 10]
[18 4 17 11 6]
[ 7 18 12 6 16]]

a[3,4]:
16

a[1:3,2:]:
[[18 4 10]
[17 11 6]]

a[:,0]:
[19 4 18 7]

a[-1]:
[ 7 18 12 6 16]

Iterating:
[19 4 18 6 5]
[ 4 16 18 4 10]
[18 4 17 11 6]
[ 7 18 12 6 16]
19
4
18
6
5
4
16
18
4
10
18
4
17
11
6
7
18
12
6
16

Copies and Views

No copies at all

a = np.arange(1,13).reshape(2,6)
print('Original Matrix:\n{}'.format(a))

print('\nb = a & modify b:')         #Wrong way to copy an array
b = a
b[:,2] = 0
print('Current A:\n{}'.format(a))
print('The result shows that B is exactly the same as A,or A & B is not independent\n')

print('\nb = a[:,:] & modify b:')   #Slicing is also a wrong way to copy an array which is different from list slicing
a = np.arange(1,13).reshape(2,6)
print('Original A:\n{}'.format(a))
b = a[:,:]
print('Current B:\n{}'.format(b))

b[:,2] = 0                        # a also changes while b is modified
print('Current A:\n{}'.format(a))
print('Current B:\n{}'.format(b))

b = 0                             #b becomes a number after this assignment
print('Current A:\n{}'.format(a))
print('Current B:\n{}'.format(b))
print('The result shows that B is exactly the same as A,or A & B is not independent\n')

Original Matrix:
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]

b = a & modify b:
Current A:
[[ 1 2 0 4 5 6]
[ 7 8 0 10 11 12]]
The result shows that B is exactly the same as A,or A & B is not independent


b = a[:,:] & modify b:
Original A:
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
Current B:
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
Current A:
[[ 1 2 0 4 5 6]
[ 7 8 0 10 11 12]]
Current B:
[[ 1 2 0 4 5 6]
[ 7 8 0 10 11 12]]
Current A:
[[ 1 2 0 4 5 6]
[ 7 8 0 10 11 12]]
Current B:
0
The result shows that B is exactly the same as A,or A & B is not independent

Correct way to copy an array

a = np.random.randint(1,10,(2,6))
print('Original Matrix:\n{}'.format(a))

print('\nb = a.copy():')
b = a.copy()
print('Current b:\n{}'.format(a))
print('\nmodify b:')
b[:,:] = 100
print('Current a:\n{}'.format(a))
print('Current b:\n{}'.format(b))

Original Matrix:
[[2 9 2 9 7 2]
[4 7 9 7 5 7]]

b = a.copy():
Current b:
[[2 9 2 9 7 2]
[4 7 9 7 5 7]]

modify b:
Current a:
[[2 9 2 9 7 2]
[4 7 9 7 5 7]]
Current b:
[[100 100 100 100 100 100]
[100 100 100 100 100 100]]

Advanced indexing and index tricks¶

Indexing with Arrays of Indices

a = np.arange(1,13)**3
print('Original Matrix a:\n{}'.format(a))
b = np.arange(2,8)
print('\nIndex Matrix b:\n{}'.format(b))
print('\na[b]:\n{}'.format(a[b]))

print('\nIndex Matrix c:\n{}'.format(c))
c = np.array([[2,4],[3,6],[7,8]])
print('\na[c]:\n{}'.format(a[c]))

Original Matrix a:
[ 1 8 27 64 125 216 343 512 729 1000 1331 1728]

Index Matrix b:
[2 3 4 5 6 7]

a[b]:
[ 27 64 125 216 343 512]

Index Matrix c:
[[2 4]
[3 6]
[7 8]]

a[c]:
[[ 27 125]
[ 64 343]
[512 729]]

palette = np.array([[0, 0, 0],         # black
                    [255, 0, 0],       # red
                    [0, 255, 0],       # green
                    [0, 0, 255],       # blue
                    [255, 255, 255]])  # white
print('Palette:\n{}'.format(palette))
image = np.array([[0,2,3],
                  [1,2,1]])
print('\nPalette[image]:\n{}'.format(palette[image]))

Palette:
[[ 0 0 0]
[255 0 0]
[ 0 255 0]
[ 0 0 255]
[255 255 255]]

Palette[image]:
[[[ 0 0 0]
[ 0 255 0]
[ 0 0 255]]

[[255 0 0]
[ 0 255 0]
[255 0 0]]]

Indexing with Boolean Arrays

a = np.arange(10).reshape(2,5)
print('Original Matrix a:\n{}'.format(a))
b = a<3
print('\nb = a<3 Matrix b:\n{}\n\nMatrix a[b]:\n{}'.format(b,a[b]))

Original Matrix a:
[[0 1 2 3 4]
[5 6 7 8 9]]

b = a<3 Matrix b:
[[ True True True False False]
[False False False False False]]

Matrix a[b]:
[0 1 2]

a = np.random.randint(1,10,(2,5))
print('Original Matrix a:\n{}'.format(a))
b = a<5
a[b] = 0
print('\nAssign all elements <5 to 0:\n{}'.format(a))

Original Matrix a:
[[7 6 9 6 3]
[2 6 1 3 4]]

Assign all elements <5 to 0:
[[7 6 9 6 0]
[0 6 0 0 0]]

a = np.arange(1,13).reshape(3,4)
print('Original Matrix a:\n{}'.format(a))
b1 = np.array([False,True,True])           # first dim selection
b2 = np.array([True,True,False,False])    # second dim selection
print('\nOriginal Matrix b1:\n{}'.format(b1))
print('\nOriginal Matrix b2:\n{}'.format(b2))

print('\na[b1,:]:\n{}'.format(a[b1,:]))
print('\na[b1]:\n{}'.format(a[b1]))
print('\na[:,b2]:\n{}'.format(a[:,b2]))

print('\na[b1,b2]:\n{}'.format(a[b1,b2]))    # take the diagonal elements of the matrix slice

Original Matrix a:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]

Original Matrix b1:
[False True True]

Original Matrix b2:
[ True True False False]

a[b1,:]:
[[ 5 6 7 8]
[ 9 10 11 12]]

a[b1]:
[[ 5 6 7 8]
[ 9 10 11 12]]

a[:,b2]:
[[ 1 2]
[ 5 6]
[ 9 10]]

a[b1,b2]:
[ 5 10]

Indexing with ix_ function(Cartesian product)

a = np.arange(1,17).reshape(4,4)
print('Original Matrix:\n{}'.format(a))
index = np.ix_([0,1],[2,3])                        #Cartesian product
print('\nnp.ix_([0,1],[2,3]):\n{}'.format(index))  #(0,2),(0,3),(1,2),(1,3)

print('\nMatrix in Cartesian product index:\n{}'.format(a[index]))

Original Matrix:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]

np.ix_([0,1],[2,3]):
(array([[0],
[1]]), array([[2, 3]]))

Matrix in Cartesian product index:
[[3 4]
[7 8]]

How to save and load NumPy objects

save( ) & load( ) => file.npy

import numpy as np
import os 
print('Current directory:\n{}\n'.format(os.path.abspath('.'))) #display the current directory

a = np.random.randint(1,11,(2,5))
print('Original Matrix a:\n{}\n'.format(a))

print('Save a to "test.npy" to the current directory\n')
np.save('test',a)                                              #Save a to "test.npy" to the current directory
             
print('load data from "test.npy" to b')
b = np.load('test.npy')                                        #load data from "test.npy" to b
print(b)

Current directory:
E:\jupyter

Original Matrix a:
[[ 1 2 10 10 6]
[ 6 1 4 6 3]]

Save a to “test.npy” to the current directory

load data from “test.npy” to b
[[ 1 2 10 10 6]
[ 6 1 4 6 3]]

savetxt( ) & loadtxt( ) => file.txt or file.csv

import numpy as np
import os 
print('Current directory:\n{}\n'.format(os.path.abspath('.'))) #display the current directory

a = np.random.randint(1,11,(2,5))
print('Original Matrix a:\n{}\n'.format(a))

print('Save a to "test.txt" to the current directory\n')
np.savetxt('test.txt',a)                                       #Save a to "test.txt" to the current directory
             
print('load data from "test.txt" to b')
b = np.loadtxt('test.txt')                                     #load data from "test.txt" to b
print(b)

Current directory:
E:\jupyter

Original Matrix a:
[[9 2 6 9 6]
[8 7 3 7 6]]

Save a to “test.txt” to the current directory

load data from “test.test” to b
[[9. 2. 6. 9. 6.]
[8. 7. 3. 7. 6.]]

How to work with Pandas

import numpy as np
import pandas as pd

a = np.arange(1,25).reshape(4,6)
print('Numpy array:\n{}\n'.format(a))
 
data = pd.DataFrame(a)        #transform an array into a dataframe
print('Pandas dataframe:\n{}'.format(data))

Numpy array:
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]
[13 14 15 16 17 18]
[19 20 21 22 23 24]]

Pandas dataframe:
0 1 2 3 4 5
0 1 2 3 4 5 6
1 7 8 9 10 11 12
2 13 14 15 16 17 18
3 19 20 21 22 23 24

How to work with Matplotlib

import numpy as np
import matplotlib.pyplot as plt

a = np.array([4,2,6,2,4,6,8,2,1,0])
plt.plot(a,'ro',)       #to plot red dots
plt.plot(a,'g')         #to plot green line

请添加图片描述

import numpy as np
import matplotlib.pyplot as plt

x = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
y = np.square(x)
plt.plot(x,y,'bo')       #to plot blue dots
plt.plot(x,y,'r')        #to plot red line
plt.xlabel('x')
plt.ylabel('y')
plt.title('quadratic function')

请添加图片描述

References

https://numpy.org/devdocs/user/quickstart.html
https://numpy.org/devdocs/user/absolute_beginners.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值