為什麼要學習Python?可以從下列TIOBE 排行看出
學習新的程式語言得先從基礎開始, 發現這種script-file language其實語法都和MATLAB, R語言 差不多
import numpy as np例如:
產生一個向量[1, 2, 3, 4]
a = np.array([1, 2, 3, 4])再來產生一個矩陣
b = np.array([[1, 2, 3],[4, 5, 6]])當然, 可以再來個transpose試試看
c = np.transpose(b)
和MATLAB語法概念相同, 觀看目前workspace變數有哪些?
whos
Variable Type Data/Info
-------------------------------
a ndarray 4: 4 elems, type `int32`, 16 bytes
b ndarray 2x3: 6 elems, type `int32`, 24 bytes
c ndarray 3x2: 6 elems, type `int32`, 24 bytes
觀察向量或陣列維度, 可以用shape
有下列結果可以知道, a預設是行向量
a.shape
Out[11]: (4,)
b.shape
Out[12]: (2, 3)
c.shape
Out[13]: (3, 2)
產生一個 2x3陣列d
d.shape = 3, –1 指定3列, 行方向元素自動計算, 結果為Out[26]
d.shpae = 3, 2 相同效果
或是d.reshape(3, 2)也可以達到
d.reshape(6, 1) 變成6x1向量, 由此可知, 跟C語言一樣, column wise(行向量方向元素先取出)
而MATLAB則是row –wise(列方向元素先取出)
d = np.array([[1, 2, 3],[4, 5, 6]])d.shape
Out[23]: (2, 3)
d.shape = 3, 2
d
Out[25]:
array([[1, 2],[3, 4],
[5, 6]])
d
Out[26]:
array([[1, 2],[3, 4],
[5, 6]])
d = np.array([[1, 2, 3],[4, 5, 6]])d
Out[28]:
array([[1, 2, 3],[4, 5, 6]])
d.shape
Out[29]: (2, 3)
d.shape = 3, -1
d
Out[31]:
array([[1, 2],[3, 4],
[5, 6]])
d.reshape(6, 1)
Out[32]:
array([[1],[2],
[3],
[4],
[5],
[6]])
取出第三列, 第一行元素值
python索引值是從0開始, 跟C語言一樣
MATLAB則是從1開始
Out[41]:
array([[1, 2],[3, 4],
[5, 6]])
In [42]: d[2][0]
Out[42]: 5
修改該元素值5->3
d[2][0]=3
d
Out[44]:
array([[1, 2],[3, 4],
[3, 6]])
資料型態
d.dtype 看起來沒有指定的話, 預設是整數型態, 因此如果事後要存浮點(floating point)會被忽略@@
d.dtype
Out[45]: dtype('int32')d[2][0] = 3.1
d.dtype
Out[47]: dtype('int32')d
Out[48]:
array([[1, 2],[3, 4],
[3, 6]])
資料格式(dtype)指定為floating point
e = np.array([[1, 2, 3],[4, 5, 6]], dtype=np.float)
e
Out[50]:
array([[ 1., 2., 3.],[ 4., 5., 6.]])
e[1][1] = 2.3
e
Out[52]:
array([[ 1. , 2. , 3. ],[ 4. , 2.3, 6. ]])
np.typeDict 顯示所有資料型態類型
np.typeDict
Out[56]:
{0: numpy.bool_,1: numpy.int8,
2: numpy.uint8,
3: numpy.int16,
4: numpy.uint16,
5: numpy.int32,
6: numpy.uint32,
7: numpy.int32,
8: numpy.uint32,
9: numpy.int64,
10: numpy.uint64,
11: numpy.float32,
12: numpy.float64,
13: numpy.float64,
14: numpy.complex64,
15: numpy.complex128,
16: numpy.complex128,
17: numpy.object_,
18: numpy.string_,
19: numpy.unicode_,
20: numpy.void,
21: numpy.datetime64,
22: numpy.timedelta64,
23: numpy.float16,
'?': numpy.bool_, 'B': numpy.uint8, 'Bool': numpy.bool_, 'Complex32': numpy.complex64, 'Complex64': numpy.complex128, 'D': numpy.complex128, 'Datetime64': numpy.datetime64, 'F': numpy.complex64, 'Float16': numpy.float16, 'Float32': numpy.float32, 'Float64': numpy.float64, 'G': numpy.complex128, 'H': numpy.uint16, 'I': numpy.uint32, 'Int16': numpy.int16, 'Int32': numpy.int32, 'Int64': numpy.int64, 'Int8': numpy.int8, 'L': numpy.uint32, 'M': numpy.datetime64, 'M8': numpy.datetime64, 'O': numpy.object_, 'O4': numpy.object_, 'Object0': numpy.object_, 'P': numpy.uint32, 'Q': numpy.uint64, 'S': numpy.string_, 'String0': numpy.string_, 'Timedelta64': numpy.timedelta64, 'U': numpy.unicode_, 'UInt16': numpy.uint16, 'UInt32': numpy.uint32, 'UInt64': numpy.uint64, 'UInt8': numpy.uint8, 'Unicode0': numpy.unicode_, 'V': numpy.void, 'Void0': numpy.void, 'a': numpy.string_, 'b': numpy.int8, 'b1': numpy.bool_, 'bool': numpy.bool_, 'bool8': numpy.bool_, 'bool_': numpy.bool_, 'byte': numpy.int8, 'bytes_': numpy.string_, 'c16': numpy.complex128, 'c8': numpy.complex64, 'cdouble': numpy.complex128, 'cfloat': numpy.complex128, 'clongdouble': numpy.complex128, 'clongfloat': numpy.complex128, 'complex': numpy.complex128, 'complex128': numpy.complex128, 'complex64': numpy.complex64, 'complex_': numpy.complex128, 'csingle': numpy.complex64, 'd': numpy.float64, 'datetime64': numpy.datetime64, 'double': numpy.float64, 'e': numpy.float16, 'f': numpy.float32, 'f2': numpy.float16, 'f4': numpy.float32, 'f8': numpy.float64, 'float': numpy.float64, 'float16': numpy.float16, 'float32': numpy.float32, 'float64': numpy.float64, 'float_': numpy.float64, 'g': numpy.float64, 'h': numpy.int16, 'half': numpy.float16, 'i': numpy.int32, 'i1': numpy.int8, 'i2': numpy.int16, 'i4': numpy.int32, 'i8': numpy.int64, 'int': numpy.int32, 'int0': numpy.int32, 'int16': numpy.int16, 'int32': numpy.int32, 'int64': numpy.int64, 'int8': numpy.int8, 'int_': numpy.int32, 'intc': numpy.int32, 'intp': numpy.int32, 'l': numpy.int32, 'longcomplex': numpy.complex128, 'longdouble': numpy.float64, 'longfloat': numpy.float64, 'longlong': numpy.int64, 'm': numpy.timedelta64, 'm8': numpy.timedelta64, 'object': numpy.object_, 'object0': numpy.object_, 'object_': numpy.object_, 'p': numpy.int32, 'q': numpy.int64, 'short': numpy.int16, 'single': numpy.float32, 'singlecomplex': numpy.complex64, 'str': numpy.string_, 'str_': numpy.string_, 'string': numpy.string_, 'string0': numpy.string_, 'string_': numpy.string_, 'timedelta64': numpy.timedelta64, 'u1': numpy.uint8, 'u2': numpy.uint16, 'u4': numpy.uint32, 'u8': numpy.uint64, 'ubyte': numpy.uint8, 'uint': numpy.uint32, 'uint0': numpy.uint32, 'uint16': numpy.uint16, 'uint32': numpy.uint32, 'uint64': numpy.uint64, 'uint8': numpy.uint8, 'uintc': numpy.uint32, 'uintp': numpy.uint32, 'ulonglong': numpy.uint64, 'unicode': numpy.unicode_, 'unicode0': numpy.unicode_, 'unicode_': numpy.unicode_, 'ushort': numpy.uint16, 'void': numpy.void, 'void0': numpy.void}初始化zeros
a = np.zeros((2,2), np.float)a
Out[64]:
array([[ 0., 0.],[ 0., 0.]])
a[0][0] = 1.2
a
Out[66]:
array([[ 1.2, 0. ],[ 0. , 0. ]])
初始化ones陣列
c = np.ones((3,2), np.float64)
c
Out[71]:
array([[ 1., 1.],[ 1., 1.],
[ 1., 1.]])
字串
取出一段字串[起始索引:結束索引]
str = 'Hello world'str[0:4]
Out[84]: 'Hell'str[1:4]
Out[85]: 'ell'str[1:]
Out[86]: 'ello world'九九乘法表
def func(i, j):
return (i+1)*(j+1)呼叫func, (2,1) 表示2列1行
a = np.fromfunction(func, (2,1))
a
Out[15]:
array([[ 1.],[ 2.]])
或是2列3行
a = np.fromfunction(func, (2,3))
a
Out[17]:
array([[ 1., 2., 3.],[ 2., 4., 6.]])
a.shape
Out[18]: (2, 3)
如果想得到9x9
a = np.fromfunction(func, (9, 9))
a
Out[20]:
array([[ 1., 2., 3., 4., 5., 6., 7., 8., 9.],[ 2., 4., 6., 8., 10., 12., 14., 16., 18.],
[ 3., 6., 9., 12., 15., 18., 21., 24., 27.],
[ 4., 8., 12., 16., 20., 24., 28., 32., 36.],
[ 5., 10., 15., 20., 25., 30., 35., 40., 45.],
[ 6., 12., 18., 24., 30., 36., 42., 48., 54.],
[ 7., 14., 21., 28., 35., 42., 49., 56., 63.],
[ 8., 16., 24., 32., 40., 48., 56., 64., 72.],
[ 9., 18., 27., 36., 45., 54., 63., 72., 81.]])
陣列和一個純量相減
a-1
Out[21]:
array([[ 0., 1., 2., 3., 4., 5., 6., 7., 8.],[ 1., 3., 5., 7., 9., 11., 13., 15., 17.],
[ 2., 5., 8., 11., 14., 17., 20., 23., 26.],
[ 3., 7., 11., 15., 19., 23., 27., 31., 35.],
[ 4., 9., 14., 19., 24., 29., 34., 39., 44.],
[ 5., 11., 17., 23., 29., 35., 41., 47., 53.],
[ 6., 13., 20., 27., 34., 41., 48., 55., 62.],
[ 7., 15., 23., 31., 39., 47., 55., 63., 71.],
[ 8., 17., 26., 35., 44., 53., 62., 71., 80.]])
存取元素 arange
(起始, 終值, 間隔)
a = 0~9
a = np.arange(10)
a
Out[37]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])從第2個開始取, 取到最後一個
a[2:]
Out[44]: array([2, 3, 4, 5, 6, 7, 8, 9])從前面開始取, 一直取到後面倒數第2個, 取到第一個
a[:-1]
Out[38]: array([0, 1, 2, 3, 4, 5, 6, 7, 8])從第一個開始取, 間隔2
a[0:9:2]
Out[24]: array([0, 2, 4, 6, 8])終值索引若超過向量元素似乎也不會有錯誤訊息跳出
這樣似乎怪怪的!!
a[0:9:3]
Out[25]: array([0, 3, 6])a[0:10:3]
Out[26]: array([0, 3, 6, 9])a[0:11:3]
Out[27]: array([0, 3, 6, 9])利用索引改變向量元素, 等號右邊的內容用逗點隔開
a[2:4] = 100, 102
a
Out[30]: array([ 0, 1, 100, 102, 4, 5, 6, 7, 8, 9])利用索引改變向量元素, 等號右邊也是一個array
a[2:4] = np.array([-1, 1])a
Out[32]: array([ 0, 1, -1, 1, 4, 5, 6, 7, 8, 9])測試等號左右兩邊的長度不一致
終值索引用-1, 表示倒數第二個(也就是9-1=8)
終值索引如果省略, 表示取到最後
a
Out[41]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])a[1:-1:2]
Out[42]: array([1, 3, 5, 7])a[1::2]
Out[44]: array([1, 3, 5, 7, 9])起始和終值索引全都省略, 間隔-1 表示索引由後往前取
a[::-1]
Out[45]: array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])最後一個開始取, 每次往前2個取
a[:0:-2]
Out[47]: array([9, 7, 5, 3, 1])起始10, 終值:1(不包含), 間隔-1
x = np.arange(10, 1, -1)
x
Out[3]: array([10, 9, 8, 7, 6, 5, 4, 3, 2])取出x索引 [2, 3, 0, 1]對應的元素, 並構成一個新的向量y
y= x[[2, 3, 0, 1]]
y
Out[6]: array([ 8, 7, 10, 9])索引也可以是負, 表示從後面數回來
z= x[[2, 3, -3, 1]]
z
Out[10]: array([8, 7, 4, 9])將z前兩筆歸零
z[0:2:1]=0
z
Out[12]: array([0, 0, 4, 9])最後兩筆變成100
起始-1(最後一筆), 終值:1(不包含), 間隔-1
z[-1:1:-1]=100
z
Out[16]: array([ 0, 0, 100, 100])取出x大於5的元素並構成新的向量
x
Out[17]: array([10, 9, 8, 7, 6, 5, 4, 3, 2])x>5
Out[19]: array([ True, True, True, True, True, False, False, False, False], dtype=bool)
x[x>5]
Out[20]: array([10, 9, 8, 7, 6])將x大於5的元素寫成0
x[x>5]=0
x
Out[23]: array([0, 0, 0, 0, 0, 5, 4, 3, 2])產生一個10x1向量, 每個元素值介於[0, 1)
z = np.random.rand(10)
z
Out[25]:
array([ 0.57139372, 0.00593147, 0.19798652, 0.90542383, 0.13065599,0.32477211, 0.20081874, 0.88151765, 0.91825765, 0.73463061])
回傳大於0.5的索引值
ind = np.nonzero(z>0.5)
ind
Out[33]: (array([0, 3, 7, 8, 9]),)回傳索引值對應的元素
z[ind]
Out[40]: array([ 0.57139372, 0.90542383, 0.88151765, 0.91825765, 0.73463061])清空 x<0.5的元素
x
Out[3]:
array([ 0.87117325, 0.17040794, 0.77082202, 0.0863664 , 0.4147697 ,0.29711409, 0.5843669 , 0.56299779, 0.05095969, 0.55264383])
x[x<0.5]=[None]
x
Out[9]:
array([ 0.87117325, nan, 0.77082202, nan, nan,nan, 0.5843669 , 0.56299779, nan, 0.55264383])
將nan的數值用0取代
ind = np.isnan(x)
x[ind] = 0
x
Out[13]:
array([ 0.87117325, 0. , 0.77082202, 0. , 0. ,0. , 0.5843669 , 0.56299779, 0. , 0.55264383])
起始0, 終值:60(不包含), 間隔10
a = np.arange(0, 60, 10)
ut[2]: array([ 0, 10, 20, 30, 40, 50])將a維度改成(-1,1)得到行向量b,
其中-1表示列方向長度不指定(由Python函式計算),1表示行方向個數等於1,
b = np.reshape(a, (-1,1))
b
Out[4]:
array([[ 0],[10],
[20],
[30],
[40],
[50]])
產生另一組列向量c
c = np.arange(0, 6)
c
Out[6]: array([0, 1, 2, 3, 4, 5])如果將b+c會發生甚麼事情?
MATLAB會告訴你資料維度不符合, 所以無法進行+運算
但Python會認為你想要進行.+
d矩陣第1行是b+c[0],
d矩陣第2行是b+c[1],
以此類推,…
d矩陣第5行是b+c[4],
d = b+c
d
Out[8]:
array([[ 0, 1, 2, 3, 4, 5],[10, 11, 12, 13, 14, 15],
[20, 21, 22, 23, 24, 25],
[30, 31, 32, 33, 34, 35],
[40, 41, 42, 43, 44, 45],
[50, 51, 52, 53, 54, 55]])
接下來, 想取出d[0, 3:5], 也就是第1列, 第4~5行
d[0, 3:5]
Out[9]: array([3, 4])想取出d[4:,4:]
就是第4列取到最後, 第4行取到最後
d[4:, 4:]
Out[11]:
array([[44, 45],[54, 55]])
想取出d所有列, 第2行
接著, 觀察d[:,2]資料長度
d[:, 2]
Out[12]: array([ 2, 12, 22, 32, 42, 52])d[:, 2].shape
Out[13]: (6,)
d[2::2, ::2]
Out[22]:
array([[20, 22, 24],[40, 42, 44]])
d[2::2, ::2]其中索引值可以由slice物件產生, 如下
slice(起始, 結束, 間隔)
ind = slice(2, None, 2), slice(None, None, 2)
ind
Out[26]: (slice(2, None, 2), slice(None, None, 2))
d[ind]
Out[27]:
array([[20, 22, 24],[40, 42, 44]])
參考資料
1. Python科學計算


留言列表
