標籤:
1 建立數組
(1) array(boject, dtype=None, copy=True, order=None, subok=False, ndmin=0)
a = array([1, 2, 3, 4])
b = array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
a.dtype --> dtype(‘int32‘)
a.shape --> (4,)
b.shape -->(3, 4)
a.shape=2, -1 #(-1時自動計算,相當於2, 6)
c = a.reshape((2,2)) #c和a公用一個空間
(2) arange([start,] stop [,step], dtype=None)
a = arange(5) -->array([0, 1, 2, 3, 4])
a[2:4] -->array([2,3])
a[:-1] -->array([0, 1, 2, 3]) #下標為負數,表示從後往前數
a[2:4] = 20, 30 -->array([0, 1, 20, 30, 4]) #可以通過下標修改元素
x = arange(5, 0, -1) -->array([5, 4, 3, 2, 1])
x[array([True, False, True, False])]
-->array([5, 3]) #只擷取布爾數組中True所在的下標 0 2 長度不夠算False
x[array([True, False, False, True, False])) = -5, -2 #用布爾數組修改True所在下標的元素
x -->array([-5, 4, 3, -2, 1])
(3) linspace(start, stop, num=50, endpoint=True, retstep=False) #等差數列的一維數組
logspane(start, stop, num=50, endpoint=True, base=10) #等比數列的一維數組
(4) frombuffer
fromfile
fromstring(string, dtype=float, count=-1, sep=‘ ‘)
fromstring(‘abcdefgh‘, int8)
-->array([ 97, 98, 99, 100, 101, 102, 103, 104], dtype=int8) #一個字元佔1個位元組(Byte)=8位(bit),
fromstring(‘abcdefgh‘, in16)
-->array([25185, 25699, 26213, 26727], dtype=int16) #25185=98*256 + 97
(5) fromfunction(funtion, shape, **kwargs)
def func(i, j):
return (i+1) * (j+1)
a = fromfunction(func, (9, 9)) --> 產生一個99乘法口訣二維數組 a[i, j] = func(i, j)
上面等價於 arange(1,10).reashape(-1,1) * arange(1,10)
Python科學計算學習一 NumPy 快速處理資料