import numpy as nppython
#### 生成ndarray數組對象(zeros,ones,eye)數組
#### 將其餘對象轉化爲ndarray數組數據結構
import numpy as np # 使用 range 函數建立列表對象 list=range(5) it=iter(list) # 使用迭代器建立 ndarray x=np.fromiter(it, dtype=float) print(x)
#### numpy從數值範圍生成數組dom
#### Numpy--結構化數據類型函數
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')]) 那麼至關於c中: struct student{ char name[20]; int age;// 8位整型數 float marks // 32位浮點數
import numpy as np student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')]) a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student) print(a) # 數組的 dtype 爲 int8(一個字節 x = np.array([1,2,3,4,5], dtype = np.int8) print (x.itemsize)
#### numpy高級索引 數組能夠由整數數組索引、布爾索引及花式索引oop
q = np.array([[1,2], [3,4], [5,6]]) y = q[[0,1,2], [0,1,0]] print y #[1, 4, 5]
2.布爾索引spa
import numpy as np x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]]) print ('大於 5 的元素是:') print (x[x > 5]) #[ 6 7 8 9 10 11] #過濾數組中的非複數元素 a = np.array([1, 2+6j, 5, 3.5+5j]) print (a[np.iscomplex(a)]) #[2.0+6.j 3.5+5.j]
3.花式索引code
import numpy as np x=np.arange(32).reshape((8,4)) print (x[np.ix_([1,5,7,2],[0,3,1,2])]) ''' 傳入多個索引數組(要使用np.ix_) [[ 4 7 5 6] [20 23 21 22] [28 31 29 30] [ 8 11 9 10]] '''
#1 a = np.arange(6).reshape(2,3) for x in np.nditer(a.T): print (x, end=", " ) for x in np.nditer(a.T.copy(order='C')): print (x, end=", " ) #輸出(倆個):0, 1, 2, 3, 4, 5, #可見a的存儲與a.T同樣在內存中 #2 a = np.arange(0,60,5) a = a.reshape(3,4) for x in np.nditer(a, op_flags=['readwrite']): x[...]=2*x print ('修改後的數組是:') 修改後的數組是: [[ 0 10 20 30] [ 40 50 60 70] [ 80 90 100 110]] #3 a = np.arange(0,60,5) a = a.reshape(3,4) print ('原始數組是:') print ('修改後的數組是:') for x in np.nditer(a, flags = ['external_loop'], order = 'F'): print (x, end=", " ) 原始數組是: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] 修改後的數組是: [ 0 20 40], [ 5 25 45], [10 30 50], [15 35 55],