前言:
首先,非常感謝Jiang老師將其分享出來!本課件非常經(jīng)典!
經(jīng)過筆者親測,竟然確實(shí)只要三天,便可管中窺豹洞見Python及主要庫的應(yīng)用。實(shí)屬難得誠意之作!
其次,只是鑒于Jiang老師提供的原始課件用英文寫成,而我作為Python的愛好者計(jì)算機(jī)英文又不太熟練,講義看起來比較慢,為了提高自學(xué)課件的效率,故我花了點(diǎn)時間將其翻譯成中文,以便將來自己快速復(fù)習(xí)用。
該版僅用于個人學(xué)習(xí)之用。
再次,譯者因工作中需要用到數(shù)據(jù)分析、風(fēng)險可視化與管理,因此學(xué)習(xí)python,翻譯水平有限,請諒解。
在征得原作者Yupeng Jiang老師的同意后,現(xiàn)在我將中文版本分享給大家。
作者:Dr.Yupeng Jiang
- 倫敦大學(xué)學(xué)院 數(shù)學(xué)系 (全球頂尖大學(xué),世界排名第7《2018QS世界大學(xué)排名》,英國第3名)
- 2016年6月5日
- [原版課件來自] https://zhuanlan.zhihu.com/p/21332075
- [中文版的說明] https://zhuanlan.zhihu.com/p/29184240
翻譯:Murphy Wan
大綱( Outline)
- 第1天:Python和科學(xué)編程介紹。 Python中的基礎(chǔ)知識: - 數(shù)據(jù)類型 - 控制結(jié)構(gòu) - 功能 - I/O文件
- 第2天:用Numpy,Scipy,Matplotlib和其他模塊進(jìn)行計(jì)算。 用Python解決一些數(shù)學(xué)問題。
- 第3天:時間序列:用Pandas進(jìn)行統(tǒng)計(jì)和實(shí)際數(shù)據(jù)分析。 隨機(jī)和蒙特卡羅。
------------------------------以下為英文原文-------------------------------------
- Day 1: Introduction to Python and scientific programming. Basics in Python: data type, contro structures, fu nctions, l/O file.
- Day 2: Computation with Numpy, Scipy, Matplotlib and other modules. Solving some maths problems with Python.
- Day 3: Time series: statistics and real data analysis with Pandas. Stochastics and Monte Carlo.
第一天的主要內(nèi)容
為【零基礎(chǔ)】的人設(shè)計(jì),帶你串一遍Python的基本操作。若你已經(jīng)get了Python的基礎(chǔ)知識,請直接去第二天的內(nèi)容 (傳送門-->第二天)
Python的背景
Python基礎(chǔ)知識
控制結(jié)構(gòu)
功能
讀/寫文件
實(shí)驗(yàn)部分
為什么使用Python ( Why Python?)
- Python是開源的,這意味著它是免費(fèi)的。
- Python是一種膠水語言:
- Python使你的編碼更加輕松
- Python平均來講,比一些語言計(jì)算更快,比如Matlab
- Python有一個很大的程序員社區(qū)。 它帶來了與大量的標(biāo)準(zhǔn)庫和擴(kuò)展包。
- Python廣泛應(yīng)用于各種行業(yè)(Google,NASA,對沖基金,銀行等)。
使用Python 2或3?
- Python 3不能向后兼容Python 2,這意味著Python 2中的某些軟件包或庫無法在Python 3中使用。
- 然而,許多機(jī)構(gòu)仍在使用Python 2,因?yàn)槿匀挥袔讉€軟件包與Python 3不兼容。
- Python 2.x是歷史遺留物,而現(xiàn)在,Python 3.x是該語言的未來。 2010年年中,2.7版本的2.7版本將不會再出現(xiàn)新的主要版本。
- 我們會遇到一些差異,但不會太多。
- 檢查https://wiki.python.org/moin/Python2 或Python3或其他在線資源獲取更多信息
一些在線資源 (Some online resources)
- http://openbookproject.net/thinkcs/python/english2e/ 通過前幾章能獲得基本思想。
- http://learnpythonthehardway.org/book/ 做練習(xí)。
- https://www.kevinsheppard.com/images/0/09/Python_introduction.pdf 強(qiáng)大的計(jì)量經(jīng)濟(jì)學(xué)重點(diǎn)。本說明的部分內(nèi)容基于本文檔。
- 對于一些特定的軟件包,如Numpy和Pandas,最好的學(xué)習(xí)方法是使用他們的官方文檔,并自己實(shí)現(xiàn)一些例子。
- 使用Google和一堆程序員相互切磋的Stack Overflow網(wǎng)站。
Python環(huán)境 (Python environment)
- 安裝Python科學(xué)堆棧的推薦方法是使用Continuum Analytics Anaconda。
- Anaconda是一個免費(fèi)的軟件包管理器,環(huán)境管理器,以及開源軟件包的集合。
- Anaconda包括核心Python解釋器和標(biāo)準(zhǔn)庫。
- https://www.continuum.io/downloads
Anaconda中包括的庫(Libararies)
- NumPy(http://numpy.scipy.org ):該庫用于處理(大)數(shù)組。
- SciPy(http://www.scipy.org ):該庫包含許多有用的科學(xué)功能。
- Matplotlib(http://matplotlib.sourceforge.net ):該庫用于繪圖。
- Pandas(http://pandas.sourceforge.net ):該庫有效并快速分析大數(shù)據(jù)集; 尤其針對金融時間序列。
- IPython(http://wprw.ipython.org ):shell、或基于瀏覽器:開發(fā)環(huán)境。
- Spyder(http://pythonhosted.org/spyder/ ):IDE交互式開發(fā)環(huán)境
管理你的Anaconda
- 在你的終端或cmd,輸入
conda list - 您可以看到已安裝的軟件包列表
- 更多的管理方法可以在這里找到: http://conda.pydata.org/docs/using/pkgs.html
你可以在本課程中學(xué)到什么?
- 本課程是為初學(xué)者設(shè)計(jì)的。 它不需要任何以前的任何編程語言的知識。
- Python編程的基礎(chǔ)知識。
- 使用Numpy,Scipy和Sympy進(jìn)行數(shù)學(xué)計(jì)算。
- 使用Matplotlib庫繪制圖形。
- 與Pandas分析實(shí)際數(shù)據(jù)和時間序列。
- 學(xué)習(xí)如何使用它作為工具。
今天的安排
- 早上:Python編程基礎(chǔ)介紹。 在上午的會議中,您將需要做一些練習(xí)。 只是一些熱身水平的問題,他們會給你一個關(guān)于Python編程的想法。
- 下午:半小時內(nèi)完成介紹部分。 那么我們會有三個大問題要解決。 他們將是今天的一個很好的總結(jié):講座。 你將有一個小時獨(dú)立工作。 然后,我將在過去半小時內(nèi)提供分析和解決方案。
練習(xí)1
安裝Anaconda并更新它以便擁有 所有包的最新版本。 我們將使用Python 3.4(而不是以前的Python 2.7版本)。
-
通過鍵入以下命令啟動Spyder并計(jì)算76:
x = 7 ** 6 打?。▁)
啟動IPython Notebook并計(jì)算7的6次方
縮進(jìn)(Indentation)
- 在某些語句之后,會加一個縮進(jìn); 縮進(jìn)減少,則表示當(dāng)前塊結(jié)束。
- 例如
x = 7 ** 6
print(x)#witt. fron't inden-tation - 這段代碼在Python中是錯誤的,雖然它在C ++,Matlab和許多其他代碼或應(yīng)用程序中是可以接受的。
編程中的一些好習(xí)慣(Some good habit in programming)
- 在需要縮進(jìn)和換行的地方使用這個功能;不要把你的腳本弄亂了。
- 不要使用沒有意義的變量;要用可以被描述的變量。
- 寫注釋。 幫助別人和自己在以后理解你現(xiàn)在所寫的代碼內(nèi)容。
- 不要同時開始學(xué)習(xí)多種編程語言。
關(guān)于Python的基礎(chǔ)知識(Basic knowlegde on Python)
常用的數(shù)字?jǐn)?shù)據(jù)類型(Common used numeric data types)
| Name | Notation | Declaration e.g. |
|---|---|---|
| Integers | int | a = 10 |
| Floating | float | b = 3.14 |
| Complex | complex | c = 1 + 2j |
| String | str | d = 'Python' |
- 備注:
- 在Python 2.7中,int與另一個int運(yùn)算將導(dǎo)致int結(jié)果。 但是,一個浮點(diǎn)運(yùn)算與int會導(dǎo)致浮點(diǎn)數(shù)。
- 在Python 3.x中,int與另一個int運(yùn)算將導(dǎo)致浮點(diǎn)數(shù)。
算數(shù)運(yùn)算符(Arithmetic operators)
| Name | Notation | Examples |
|---|---|---|
| Addition | + | a + b |
| Subtraction | - | c - b |
| Multiplication | * | x*y |
| Division | / | x/z |
| Modulus | % | x%a |
| Exponent | ** | a**x |
練習(xí)2(Exercise 2)
- 猜下面代碼的結(jié)果。執(zhí)行他們,看答案。
- Try to guess the results of the following code. Implement them and check your answers.
- a = 10 # int
- b = 3.14 # fLoat
- c = 3 #int
- d = a ** 2 # square of a
- print (type (d)) # return the type of d
- print (type (d/l0)) # return the type of d/l0
- print (type (a/b)) # return the type of a/b
- print (type (a/c)) # return the type of a/c
- print (type (bd)) # return the type of bd
浮點(diǎn)數(shù)的精度(Precision of float)
- 嘗試在您的控制臺中鍵入0.1 + 0.2。 你會發(fā)現(xiàn)這個值是
- 0.30000000000000004
- 這是二進(jìn)制浮點(diǎn)的本質(zhì)。 您可以在支持硬件浮點(diǎn)運(yùn)算的所有語言中看到同樣的東西。
- 可以使用“round()”功能控制顯示精度,但也有上述情況,這意味著round(9.995,2)返回9.99而不是10,因?yàn)?.995的存儲稍小于9.995。
- decimal Library將給出精確的存儲值,請參見以下示例。
例子(Example)
import decimal
# import the libray "decimal"
# display 2 decimal precision
print (round (3*1415 , 2)) # result 3. 14
print (round (9 .995 , 2)) # result 9. 99
#call function "Decimal " from lib "decimal"
print (decimal.Decimal (9.995))
The last "print" returns
9.9949999999999992184029906638897955417633056640625,
which is exactly how 9.995 is stored in the hardware.
練習(xí)3:字符串str的一些功能(Exercise3:Some functions for str)
t = 'He is a string. Who are you?'
print(t.capitalize()) # Cap first letter
print(t.split()) # split by words
print(t.find('i')) # return index of 'i'
print(t.find('in')) # index of 'i' in 'in'
print(t.find('Python')) # find sth not in
print(t[0:4]) # returu from index 0 to 3
print(t.replace(' ','|')) # replace by '|'
w = 'http://www.google.com'
print(w.strip('http://')) #delete sth
He is a string. who are you?
['He', 'is', 'a', 'string.', 'Who', 'are', 'you?']
11
-1
He i
He|is|a|string.|Who|are|you?
www.google.com
Python功能:索引(Python features: Indexing)
- Python具有與C ++類似的索引規(guī)則,其起始索引為0。
- 當(dāng)通過索引返回值時,間隔實(shí)際上是[,]樣式,這意味著不包括終端索引。
基本的數(shù)據(jù)結(jié)構(gòu)(Basic data structures)
| Name | Nation | Declaration e.g. |
|---|---|---|
| Tuple | tuple | b = (1,2.5, 'data') |
| List | list | c = [1,2.5,'data'] |
| Dictionary | dict | d = {'Name': 'Kobe', 'Country':'US'} |
| Set | set | e = set(['u','d','ud','d','du']) |
- 元組(tuple)只有幾種方法可以更改。
- 列表(list)比元組更靈活。
- 字典(dict)是一個鍵值對存儲對象。
- 集合(set)是對象中唯一的無序集合對象。
列表的一些有用功能(Some useful functions for list)
l = [1, 2, 3.14, 'data'] #list
print (type(l))l.append ([4, 3])
print(l)l.extend (['delta' ,5 ,6] ) #add a list
print(l)l.insert(3, 'beta') #insert before index 3
print(l)l.remove ('data') #delete an elementprint(l)
<class 'list'>
[1, 2, 3.14, 'data', [4, 3]]
[1, 2, 3.14, 'data', [4, 3], 'delta', 5, 6]
[1, 2, 3.14, 'beta', 'data', [4, 3], 'delta', 5, 6]
[1, 2, 3.14, 'beta', [4, 3], 'delta', 5, 6]
Python功能:參考對象(Python features: Refer for object)
- 在Python中,如果要將值從一個對象傳遞給另一個對象,則=(等號)將按地址傳遞值。
- 例如,
x = [1, 2. 3, 4]
y = x
y[0] = 5
print(x)
x = [1, 2, 3, 4]
z = x.copy()
z[0] = 5
print (x)
輸出將會是[5,2,3,4],[1,2,3,4]
多維列表(Multidimensional list)
- 我們可以創(chuàng)建一個包含多行的列表
a = [[1,2 , 3 ,4],[1,2 ,3,4],[1,2 ,3]]
print(a)
print(a[0][3])
- 但請注意:
多維列表不是矩陣。 數(shù)學(xué)運(yùn)算符可能會導(dǎo)致您不想看到的結(jié)果。 對于矩陣計(jì)算,我們將在明天花費(fèi)大量的時間。
條件語句(Conditions)
- 條件控制元素包括if,else和elif。
- 對于條件語句,我們有如下幾種:
| Name | Notation |
|---|---|
| larger | > |
| smaller | < |
| equal | == |
| larger or equal | >= |
| sma |
- 對于多條件同時使用的情況,我么使用and, or 或者 not作為關(guān)鍵字來相互銜接
示例和練習(xí):條件語句 (Example & exercise: conditions)
a = [24, 16, 54]
b = []
if a[0]< a[1] and a[0]< a[2] :
b.append(a[0])
if a[1] < a[2]:
b.append(a[1])
b.append(a[2])
else:
b.append(a[2])
b.append(a[1])
# This piece of code is not done yet.
# Please complete it !!!
循環(huán)語句 (Loops)
- 循環(huán)語句有很多不同的樣式代碼,我們只提供兩個常用的語句。
for...in ... :statement A
是循環(huán)中最常用的語句,通常與range(start,end,step)一起使用,start為起始值,end為結(jié)束值,step為步長。 例如,
range(0,8,1) 給出[0,1,2,3,4,5,6,7]
2/
while ...:statement A
將會執(zhí)行A語句,直到滿足while的條件。
舉例:循環(huán)語言(Example: loops)
# for和range的例子 example of for and range
# 初始值默認(rèn)值為default start of range is O
# 步長默認(rèn)值為default step of range is 1
for i in range(2, 10, 3):
print(i)
l= i**2
print(l)
# white to sum up 1 to 100
a = 0
sumup = O
while a < 100 :
a + 1
sumup += a
print ( sumup)
break和continue.
- 你可以在循環(huán)語句中使用關(guān)鍵字break,以跳出循環(huán)。(you can use the keyword break inside a loop to leave the loop..)
- 你也可以在循環(huán)語句中使用關(guān)鍵字continue,以暫停當(dāng)前循環(huán)執(zhí)行后面的語句。(you can use the keyword continue inside a loop to stop pracessing the current iteration of the loop and immediately go on to the next round.)
- 舉例 E.g.
# search the first
# be divided by 17
for i in range(300, 351):
if i % 17 == O:
print (i)
break
else :
cantinue
循環(huán)語句嵌套(Loop inside the loop)
- 循環(huán)語句可以內(nèi)嵌在另一個循環(huán)語句中(Loop can be written inside another loop)
for i in range (10):
print (i)
for j in range (5):
print (j)
練習(xí)(Exercises)
- 計(jì)算從1到1000的累計(jì)值。
- 計(jì)算從1到1000的偶數(shù)之和。
功能 (Functions)
功能(方法or函數(shù))的聲明 (Function declaration)
- 方法定義如下(Functions are defined as)
def TheNameOfFunction(paral, para2):
...
return Outcome
- 函數(shù)(方法)返回的輸出結(jié)果會在函數(shù)被調(diào)用的地方出現(xiàn)。
舉例:求兩個變量最大值的函數(shù)
def MaxOfTwo (x1, x2):
if x1 >= x2:
return x1
else:
return x2
a = l
b = 2
c = MaxOfTwo(a, b)
print(c)
默認(rèn)參數(shù)
- Python中的函數(shù)沒有函數(shù)重載(function overloading)。 這意味著你不能有兩個共享同名的功能。 但是操作符重載(operator overloading)是正常的。
- 您可以為函數(shù)的參數(shù)提供默認(rèn)值,例如。
def MaxOfTwo(xl, x2 = 1): ...
- 請將您的默認(rèn)參數(shù)放在一堆函數(shù)參數(shù)的末尾處。
具有兩個輸出的函數(shù)(方法)
- 函數(shù)還可以返回兩個或多個輸出。 在這種情況下,你應(yīng)該這樣寫出代碼:
def f (x1, x2, x3, ...):
......
return(y1, y2, y3, ...)
a1,b1,c1 = f(...)
讀取/寫入文件 (Reading/ writing files)
內(nèi)建open()方法 [Built-in open() function]
- 要打開一個文件,使用Python內(nèi)建的open()函數(shù)。 open()方法返回一個文件對象,最常用的一般使用兩個參數(shù)。
file_object = open(filename, mode)
- 這個mode參數(shù)可以是(The mode can be)
- 'r' 只讀模式(when the file will only be read)
- 'w' 只寫模式(與一個現(xiàn)存文件文件同名,則被清除)
- 'a' 添加模式,即任意寫入文件的數(shù)據(jù)都被自動添加到末尾
- 'r+' 打開文件,可以讀、寫
創(chuàng)建一個文件 (Creating new file)
file = open('newfile.txt', 'w')
file.write('I am created for the course. \n')
file.write('How about you? ')
file.write('How is your exam?')
file.close()
讀取一個文件 (Reading a file)
file = open('newfile.txt', 'r')
#show whole efile
print(file.read())
#show first ten characterrs
print(file.read(10))
#view by line
print(file.readline())
#view all by line
print(file.readlines())
file.close()
循環(huán)讀取一個文件 (Looping over a file object)
file = open('newfile.txt', 'r')
for line in file:
print (line)
file.close()
輸出將是
我是為這個課程而誕生的
你怎么樣?你的考試如何
* ------以下是英文原文--------------------
Output would be:
I am created for the course
How about you? How is your exam?
增加一個文件 (Adding in a file)
file = open('newfile.txt', 'a')
file.write('\nI am back again. \n')
file.write('Do you miss me?\n')
file.clase()
with語句 (The with statement)
- 很容易忘記關(guān)閉{close()}文件。 由于這個和其他原因,最好使用with語句:
with open(“humpty.txt”) as f:
- 這樣可以確保文件正確關(guān)閉,即使讀取時發(fā)生錯誤。
文件路徑 (File paths)
- 也可以使用絕對路徑指定文件名。
- 示例(Mac / Linux):
open ('/etc/gimp/2.O/gtkrc')
- 示例(Windows):
open('C:\Users\user\Documents\file.txt')
- 請注意,反斜杠需要轉(zhuǎn)義(寫入兩次'\')
實(shí)驗(yàn)部分 (Lab Session)
目標(biāo)1 (Target 1)
您的老板要求您編寫一段代碼,以便對于具有float或int類型元素的任何長度列表(list),您的函數(shù)可以將它們按照從大到小排序。
例如 如果你的老板給一個list
[8, 2, 4, 6, 1, 9, 0, 3, 5, 7]
- 你的方法將返回
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
目標(biāo)1提示: (Hint for Target 1:)
-
有三種不同的排序算法:
- 氣泡排序:從最后開始,將最后兩次的最大值傳遞給前一個索引。 你第一次遍歷每一個數(shù)字,你通過最大的數(shù)字到一開始。 然后你在剩下的數(shù)字中重復(fù)一遍。
- 選擇排序:首先搜索整個列表。 并將最小的數(shù)字傳遞到列表的末尾。 然后搜索整個列表排除最后一個數(shù)字。 再重復(fù)該步驟。
- 插入排序:從一開始,按順序比較第一個數(shù)字和第二個數(shù)字,將第一個數(shù)字交換為最大數(shù)字。 然后重復(fù)它構(gòu)成第二個直到結(jié)束。
-----以下為英文原文-----
There are three different algorithms of sorting:
- Bubble sort: Starting from the end, pass the maximum of last two to the former index. The first time you traverse every number, you pass the largest number to the beginning. Then you repeat them in the rest numbers.
- Selectian sort: Search the whole list first. And pass the smallest number to the end af the list. Then search the whole list exclude the last number. Repeat it.
- Insert sort: Starting from the beginning, compare the first number and the rest sequentially to swap the first number to be the biggest. Then repeat it fram the second one until end
目標(biāo)2 (Target 2)
-
代碼功能
- 3days_img01.gif
使用派生詞的定義,對其數(shù)字導(dǎo)數(shù)函數(shù)進(jìn)行編碼。
-
找到數(shù)值解
- 3days_img02.gif
通過二等分法。
-
通過Newton-Raphson方法再次解決,該方法是“根搜索”的另一種數(shù)值方法。 它是由...給出的
- 3days_img03.png
目標(biāo)2的提示 (Hint for Target 2:)
-
衍生物可以近似于
- 3days_img04.gif
- 3days_img05.gif
- 3days_img06.gif
- 二分法實(shí)現(xiàn)如下:
- 給出間隔[a,b],使得f(a)和f(b)具有不同的符號。
- 計(jì)算中點(diǎn)c = 0.5 (a + b)和中點(diǎn)f(c)的函數(shù)值。
- 如果f(x)足夠,則停止。 否則,將(a,f(a))或(b,f(b))替換為(c,f(c)),以便在新間隔內(nèi)存在過零點(diǎn)
-----以下為英文原文-----
-
The derivative can be appraximated by
- f'(x) ≈ [f(x + h) - f (x)]/h,
- f'(x) ≈ [f(x + h) - f(x - h)]/h,
- f'(x) ≈ [f(x+h) - f (x-h)]/2h
-
Bisection is implemented as:
- Give an interval [a, b] such that f(a) and f(b) have different sign.
- Calculate the midpoint c= 0.5 * (a + b) and the functian value at the midpoint, f(c).
- If f(x) is goad enough, stop. Otherwise replace either (a, f(a)) or (b, f(b) with (c, f(c)) so that there is a zero crossing within the new interval
目標(biāo)3 (Target 3)
- 在面試時 ,你的面試官者要求你編寫一個可以給他第n個斐波納契數(shù)字的函數(shù),其中n由你的面試官決定。
- In your interview. your interviewer ask yau to code a function that could give him the n-th Fibonacci number, where n is determined by your interviewer.
目標(biāo)3提示: (Hint for Target 3:)
-
斐波那契序列如下
- 3days_img07.gif
- 3days_img08.gif
其中一個方法是遞歸地使用一個函數(shù)。
其中一個方法是利用append()函數(shù)。
-----以下為英文原文-----
-
Fibonacci sequence is given like
ao = 1, a1 = 1,
an = an-1 + an-2 for n> 2
One of the method is to recursively use a function.* One of the method is to take advantage from append() function.
第一天的課程到此結(jié)束,辛苦了







