阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。
Objectives
- Learn Colaboratory fundanmental operations
- Learn and Review Python Basics
- Learn Numpy Basics
Things need to know
- 对于0基础的同学,以了解为主
- 不需要可以从0把code写出来
- 这部分code与算法课程code的思维不一样
- 需要下课自己去跑一下code,尽量去理解
- 工具终归是辅助我们的,先尽力学会一个
- 逐步掌握python code debug能力
Introduction to Colaboratory
- Install Colaboratory (check class doc)
- Install and import python packages
#@title import packages
import numpy as np #numpy
import pandas as pd #pandas#@title install packages(不需要掌握)
!pip install pandasqlRequirement already satisfied: pandasql in c:\users\[USER]\anaconda3\envs\myenv\lib\site-packages (0.7.3)
Requirement already satisfied: pandas in c:\users\[USER]\anaconda3\envs\myenv\lib\site-packages (from pandasql) (1.2.4)
Requirement already satisfied: numpy in c:\users\[USER]\anaconda3\envs\myenv\lib\site-packages (from pandasql) (1.21.0)
Requirement already satisfied: sqlalchemy in c:\users\[USER]\anaconda3\envs\myenv\lib\site-packages (from pandasql) (1.4.22)
Requirement already satisfied: python-dateutil>=2.7.3 in c:\users\[USER]\anaconda3\envs\myenv\lib\site-packages (from pandas->pandasql) (2.8.1)
Requirement already satisfied: pytz>=2017.3 in c:\users\[USER]\anaconda3\envs\myenv\lib\site-packages (from pandas->pandasql) (2021.1)
Requirement already satisfied: six>=1.5 in c:\users\[USER]\anaconda3\envs\myenv\lib\site-packages (from python-dateutil>=2.7.3->pandas->pandasql) (1.16.0)
Requirement already satisfied: greenlet!=0.4.17 in c:\users\[USER]\anaconda3\envs\myenv\lib\site-packages (from sqlalchemy->pandasql) (1.1.0)
Python Basics
Numeric Types
x = 2 # =>2
print(type(x)) # class 'int'
y = 1.5 # =>1.5
print(type(y)) # class 'float'
# Math
x = x ** 3 # =>8 exponential
print(x)
x += 1 # =>9 addition x = x + 1
print(x)
x %= 2 # =>1 modulo
print(x)
x += y # =>2.5 x = x + y
print(x)<class 'int'>
<class 'float'>
8
9
1
2.5
Boolean
t = True
f = False
print(type(t)) # class 'bool'
print(t or f) # True
print(t and f) # False
print(not t) # False
print(not f) # True
# or:返回第一个不是false的值
print(1 or False) # (Advanced, just know it is enough, is it really important?)
test = 1 or False
print(type(test))
print(test)<class 'bool'>
True
False
False
True
1
<class 'int'>
1
String
Strings are immutable type, which means we can’t change the value once initialized.
# Construct string
s1 = 'single quote' # use single quotes
print(type(s1)) # class 'str'
s2= "double quote" # use double quotes
print(type(s2)) # class 'str'<class 'str'>
<class 'str'>
# String concatenation
s3 = s1 + ' and ' + s2 # string concatenation
print(s3)
#s1 + 1?
s1 + str(1)
#single quote1single quote and double quote
'single quote1'
# String useful functions
# escape \
print('Caplitalize the string: ' + s3.capitalize()) # Caplitalize the string
print('Uppercase the string: ' + s3.upper()) # Uppercase the string
print('\'o\' occurrences: ' + str(s3.count('o'))) # Count the occurrences of a character
print('first \'te\' index: ' + str(s3.index('te'))) # The lowest index of the occurrenceCaplitalize the string: Single quote and double quote
Uppercase the string: SINGLE QUOTE AND DOUBLE QUOTE
'o' occurrences: 3
first 'te' index: 10
print(s3[1]) # string indexingi
# (Advanced)Tripe Quotes
s = '''
You can specify multi-line string.
This is an example.
'''
print(s)
You can specify multi-line string.
This is an example.
# (Advanced)String format
# escape {{}} 不用管
# https://docs.python.org/3/library/string.html#formatstrings
s = "{} is handsome, but {} is not"
print(s.format('Rayman','Jason'))
s = "{1} is handsome, but {0} is not, {2} is super handsome"
print(s.format('Jason', 'Rayman', 'Mike'))
name1 = 'Rayman'
name2 = 'Jason'
# 1000lines
s = "{n1} is handsome, but {n2} is not"
print(s.format(n2 = name2, n1 = name1))Rayman is handsome, but Jason is not
Rayman is handsome, but Jason is not, Mike is super handsome
Rayman is handsome, but Jason is not
List
List is mutable type
lst1 = [] # initialize an empty list
print(type(lst1)) # class 'list'
lst2 = [1, 2, 3, 4] # create a list with same data type values
print(lst2)
lst3 = ['one', 2, 'three', 4] # create a list with different data type values
print(lst3)<class 'list'>
[1, 2, 3, 4]
['one', 2, 'three', 4]
lst2.append(5) # append a new element to end of the list
print(lst2)
lst2.pop(3) # remove the 4th element of the list
print(lst2)
lst2[2] = 100 # list is mutable
print(lst2)[1, 2, 3, 4, 5]
[1, 2, 3, 5]
[1, 2, 100, 5]
print(lst2[0]) # list indexing
print(lst2[-1]) # negative index, access from end of list
print(len(lst2)) # the length of list
print(lst2 + lst3) # list concatenation1
5
4
[1, 2, 100, 5, 'one', 2, 'three', 4]
Slicing
lst = range(6) # create an list of numbers using built-in function range
print(type(lst)) # class 'range'
lst = list(lst) # change to list
print(type(lst)) # class 'list'
# [start(inclusive) : end(exclusive) : step]
print(lst) # [0, 1, 2, 3, 4, 5]
print(lst[0:6]) # index from 0 to 5, [0, 1, 2, 3, 4, 5]
print(lst[1:]) # index from 1 to the end, [1, 2, 3, 4, 5]
print(lst[:4]) # index from start to 4(exclusive), [0, 1, 2, 3]
print(lst[:]) # the whole list, [0, 1, 2, 3, 4, 5]
print(lst[:-1]) # negative index slicing, [0, 1, 2, 3, 4]
print(lst[-1:]) # negative index slicing, [5]
print(lst[::2]) # change index step to 2, [0, 2, 4]
lst[2:4] = [3, 2] # modify the values by slicing
print(lst) # [0, 1, 3, 2, 4, 5]<class 'range'>
<class 'list'>
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[0, 1, 2, 3]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4]
[5]
[0, 2, 4]
[0, 1, 3, 2, 4, 5]
print(lst[:-1]) # negative index slicing, [0, 1, 2, 3, 4]
print(lst[:5]) # negative index slicing, [0, 1, 2, 3, 4]
print(lst[-1:]) # negative index slicing, [5]
print(lst[5:]) # negative index slicing, [5][0, 1, 3, 2, 4]
[0, 1, 3, 2, 4]
[5]
[5]
# [start(inclusive) : end(exclusive) : step]
print(lst)
print(lst[::-2])[0, 1, 3, 2, 4, 5]
[5, 2, 1]
ss = 'Hello World!' # initialize a string
print(ss)
print(ss[:]) # the whole list
print(ss[1:3]) # index from 1 to 2Hello World!
Hello World!
el
Tuple
A tuple is an (immutable) ordered list of values. A tuple is in many ways similar to a list; one of the most important differences is that tuples can be used as keys in dictionaries and as elements of sets, while lists cannot.
整理注: tuple只有在全部成员可哈希时才能作为字典键。随机输出和dtype属于原环境记录,不保证在其他平台逐字复现。
t = (21, 42) # create a tuple
print(type(t))<class 'tuple'>
Dictionary
{key: value}
key-value pairs
skills = ['ML', 'Stat', 'Coding', 'Business']
scores = [90, 80, 1, 59]
print(scores[skills.index('Coding')]) # Time Complexity
score_dict = {'ML': 90, 'Stat': 80, 'Coding': 1, 'Business': 59} # create a dictionary
print(score_dict['ML']) # get ML score
print('Stat' in score_dict) # check if 'Stat' in the dictionary
score_dict['Spark'] = 70 # Add a new key-value pair to the dictionary
print(score_dict['Spark'])
print("current score:" + str(score_dict['Coding']))
score_dict['Coding'] = 100 # Modify the existing value in the dictionary
print("afterwards: " + str(score_dict['Coding']))
score_dict.pop('Spark')1
90
True
70
current score:1
afterwards: 100
70
Set
A set is an unordered collection of distinct elements.
skills = {'ML', 'Stat', 'Coding', 'Business'}
skills_list = ['ML', 'Stat', 'Coding', 'Business']
print('Business' in skills) # check if an element is in a set
print('Spark' in skills_list) # False
skills.add('Spark') # add an element
print(skills)
skills.remove('Spark') # remove an element
print(skills)True
False
{'ML', 'Spark', 'Coding', 'Business', 'Stat'}
{'ML', 'Coding', 'Business', 'Stat'}
Numpy
NumPy is the fundamental package for scientific computing in Python. It is a Python library that provides a multidimensional array object, various derived objects (such as masked arrays and matrices), and an assortment of routines for fast operations on arrays.
At the core of the NumPy package, is the ndarray object. This encapsulates n-dimensional arrays of homogeneous data types, with many operations being performed in compiled code for performance.
Arrays
lst = [[1, 2, 3], [4, 5, 6]] # 2x3
print(lst)
a = np.array(lst) # create array from lists
print(type(a)) # class 'numpy.ndarray'
print(a)
print(a[0]) # first row
print(a[0][1]) # first row, second column
print(a.shape) # 2 x 3
print(a.ndim) # 2 dimensions
print(a.dtype) # data type of the elements of array
print(a.size) # total number of elements in the matrix[[1, 2, 3], [4, 5, 6]]
<class 'numpy.ndarray'>
[[1 2 3]
[4 5 6]]
[1 2 3]
2
(2, 3)
2
int32
6
# useful functions to create numpy array
b = np.arange(0, 10, 2, dtype='float') # create 1d array, [start, stop)
print(type(b)) # class 'numpy.ndarray'
print(b)
print(b.shape) # (5) + 2
print(type(b.shape))
c = np.linspace(1.5, 2.5, 9) # create 1d array with float, [start, stop]
print(type(c)) # class 'numpy.ndarray'
print(c)
print(c.shape)
d = np.zeros((2, 3)) # all zeros
print(type(d)) # class 'numpy.ndarray'
print(d)
e = np.ones((2, 3), dtype='int') # all ones
print(type(e)) # class 'numpy.ndarray'
print(e)
f = np.full((2, 3), 9) # constant matrix
print(type(f)) # class 'numpy.ndarray'
print(f)
g = np.eye(3) # 3 x 3 identity matrix
print(type(g)) # class 'numpy.ndarray'
print(g)<class 'numpy.ndarray'>
[0. 2. 4. 6. 8.]
(5,)
<class 'tuple'>
<class 'numpy.ndarray'>
[1.5 1.625 1.75 1.875 2. 2.125 2.25 2.375 2.5 ]
(9,)
<class 'numpy.ndarray'>
[[0. 0. 0.]
[0. 0. 0.]]
<class 'numpy.ndarray'>
[[1 1 1]
[1 1 1]]
<class 'numpy.ndarray'>
[[9 9 9]
[9 9 9]]
<class 'numpy.ndarray'>
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
print(d)
print(d.shape)[[0. 0. 0.]
[0. 0. 0.]]
(2, 3)
j = d.reshape((3,2))
print(j)
print(j.shape)
print(j.dtype)[[0. 0.]
[0. 0.]
[0. 0.]]
(3, 2)
float64
j1 = d.reshape((3,2,1))
print(j1)
print(j1.shape)
print(j1.dtype)[[[0.]
[0.]]
[[0.]
[0.]]
[[0.]
[0.]]]
(3, 2, 1)
float64
(5,)是一维数组,(1, 5)和(5, 1)都是二维
print(b)
print(b.shape)[0. 2. 4. 6. 8.]
(5,)
# reshape
h = b.reshape((5, 1))
print(h)
print(h.shape)[[0.]
[2.]
[4.]
[6.]
[8.]]
(5, 1)
# reshape
h1 = b.reshape((1, 5))
print(h1)
print(h1.shape)[[0. 2. 4. 6. 8.]]
(1, 5)
Indexing and Slicing
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(a)
# [ , ]
# Use slicing to pull out the subarray consisting of the first 2 rows
# and columns 1 and 2; b is the following array of shape (2, 2):
# [[2 3]
# [6 7]]
# start(inclusive) : end(exclusive) : step
b = a[:2, 1:3]
print(b)
print(a[1]) # access a row
print(a[:, 1:2]) # access a col
print(a[1, 1]) # access single value[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[2 3]
[6 7]]
[5 6 7 8]
[[ 2]
[ 6]
[10]]
6
# boolean masking
# and &
# or |
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(a)
a_idx1 = (a <= 5) # return the boolean array that satisfies the conidtion
print(a_idx1)
a_idx2 = (a >=5) & (a <= 10) # return the boolean array that satisfies the conidtion
print(a_idx2)
#and a and b
print(a[a_idx1]) # return the corresponding array
print(a[a_idx2]) # return the corresponding array
print(a[(a > 5) & (a < 10)]) # single statement
print(type(a[(a > 5) & (a < 10)])) # <class 'numpy.ndarray'>[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[ True True True True]
[ True False False False]
[False False False False]]
[[False False False False]
[ True True True True]
[ True True False False]]
[1 2 3 4 5]
[ 5 6 7 8 9 10]
[6 7 8 9]
<class 'numpy.ndarray'>
Math
import numpy as np
a = np.array([[10, 11, 12], [13, 14, 15]])
#print(a.shape)
print(a)
b = np.arange(1, 7).reshape((2, 3))
#print(b.shape)
print(b)
# element-wise calculation:
print(a + b)
print(a - b)
print(np.add(a, b))
print(a * b)
# Matrix product
print(np.dot(a, b.transpose())) # 2x3, 3x2
#a.dot(b.transpose())
print(a.T.dot(b)) # 3x2, 2x3
#np.dot(a.T, b)[[10 11 12]
[13 14 15]]
[[1 2 3]
[4 5 6]]
[[11 13 15]
[17 19 21]]
[[9 9 9]
[9 9 9]]
[[11 13 15]
[17 19 21]]
[[10 22 36]
[52 70 90]]
[[ 68 167]
[ 86 212]]
[[ 62 85 108]
[ 67 92 117]
[ 72 99 126]]
print(a)
print(b.transpose())
print(a.dot(b.T))[[10 11 12]
[13 14 15]]
[[1 4]
[2 5]
[3 6]]
[[ 68 167]
[ 86 212]]
print(a)
print(a.T)
print(a.transpose())[[10 11 12]
[13 14 15]]
[[10 13]
[11 14]
[12 15]]
[[10 13]
[11 14]
[12 15]]
# Matrix multiplication
# print(a, a.shape)
# print(b, b.shape)
# axb dot bxc -> axc
# 2x3 dot 3x4 -> 2x4
# 3x2 dot 2x3 -> 3x3
#print(a.T, a.T.shape)
#print(b, b.shape)
#print(a.T.dot(b))# calculation along row or column index, calculate by the index of the axis which is set
# Axis 0 will act on all the ROWS in each COLUMN
# Axis 1 will act on all the COLUMNS in each ROW
# check this link for axis https://stackoverflow.com/questions/22149584/what-does-axis-in-pandas-mean
# https://stackoverflow.com/questions/25773245/ambiguity-in-pandas-dataframe-numpy-array-axis-definition
print(a)
print(np.sum(a))
print(np.sum(a, axis = 0)) #x axis
print(np.sum(a, axis = 1)) #y axis[[10 11 12]
[13 14 15]]
75
[23 25 27]
[33 42]
Random
# generate random number
import numpy as np
print(np.random.rand(2,2)) # Random numbers between [0,1) of shape 2,2
print(np.random.randn(2,2)) # Normal distribution with mean=0 and variance=1 of shape 2,2
print(np.random.randint(0, 10, size=[2,2])) # Random integers between [0, 10) of shape 2,2
print(np.random.random()) # One random number between [0,1)
print(np.random.random(size=[2,2])) # Random numbers between [0,1) of shape 2,2
print(np.random.choice(['a', 'e', 'i', 'o', 'u'], size=10)) # Pick 10 items from a given list, with equal probability
print(np.random.choice(['a', 'e', 'i', 'o', 'u'], size=10, p=[0.3, 0.1, 0.1, 0.4, 0.1])) # Pick 10 items from a given list with a predefined probability 'p'
print(np.random.choice(np.arange(100), size=[10,3], replace=True)) # get 10x3 random samples from [0-99] with replacement
#replace = True --> sampling w. replacement
#replace = False --> sampling w.o. replacement[[0.75312481 0.04110822]
[0.78922707 0.79438021]]
[[0.26000059 0.78053916]
[1.41481541 0.40713943]]
[[6 8]
[5 7]]
0.36945022213513723
[[0.90204886 0.66848155]
[0.01227775 0.71448134]]
['e' 'u' 'u' 'i' 'e' 'o' 'e' 'e' 'u' 'e']
['o' 'a' 'a' 'o' 'o' 'a' 'e' 'o' 'a' 'e']
[[39 91 84]
[65 5 97]
[50 30 80]
[61 76 23]
[70 13 7]
[38 66 30]
[89 98 4]
[40 95 91]
[56 25 13]
[20 69 64]]
import numpy as np
import pandas as pd#(Advanced) use random generator to do train/test split
url="https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/d546eaee765268bf2f487608c537c05e22e4b221/iris.csv"
iris = pd.read_csv(url)
#print(iris.head())
#print(iris.info())
# Split data into training and testing
iris_idx = np.arange(iris.shape[0])
#np.arange(5). --> [0,1,2,3,4]
print(iris.shape)
print(iris.shape[0])
num_training = int(np.floor(0.75 * iris.shape[0]))
print(num_training)
iris_train_idx = np.random.choice(iris_idx, size=num_training, replace=False)
iris_test_idx = np.delete(iris_idx, iris_train_idx)
iris_train = iris.iloc[iris_train_idx]
iris_test = iris.iloc[iris_test_idx]
#print(iris_train.info())
#print(iris_test.info())(150, 5)
150
112
iris.head() sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa
# (Advanced)use sklearn to spilt data
#import sklearn.model_selection as ms
from sklearn.model_selection import train_test_split
X = iris.drop('species', axis = 1)
y = iris['species']
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify = y, test_size=0.25, random_state = 2)
print(X_train.info())<class 'pandas.core.frame.DataFrame'>
Int64Index: 112 entries, 147 to 123
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 sepal_length 112 non-null float64
1 sepal_width 112 non-null float64
2 petal_length 112 non-null float64
3 petal_width 112 non-null float64
dtypes: float64(4)
memory usage: 4.4 KB
None
# (Advanced) A random seed (random_state)
# random.seed() is a number (or vector) used to initialize a pseudorandom number generator.
# generate the deterministic random data
a = np.random.RandomState(8)
print(type(a))<class 'numpy.random.mtrand.RandomState'>
a.randint(1000)451
a.randint(1000)340
a.randint(1000)361