python編程入門----numpy不常見的小細節

import numpy as nppython

#### 生成ndarray數組對象(zeros,ones,eye)數組

  1. np.zeros(5) == np.zeros((5,)) #意思都是建立numpy的一維數組,該例的答案是[0,0,0,0,0],(5,)表示第一個參數
  2. a=random.randn(2,3) # 建立 randn(size) 服從 X~N(0,1) 的正態分佈隨機數組
  3. b=random.randint([low,high],size) #建立在[low, high]間的數組;a=random.randint(100,200,(3,3))

#### 將其餘對象轉化爲ndarray數組數據結構

  1. numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0) #接受 buffer 輸入參數,以流的形式讀入轉化成 ndarray 對象。
  2. numpy.asarray((1,2,3)) #將元組變爲ndarray
  3. numpy.fromiter(iterable, dtype, count=-1) #從可迭代對象中創建 ndarray 對象,返回一維數組
  • 例:
import numpy as np 
# 使用 range 函數建立列表對象
list=range(5)
it=iter(list)     
# 使用迭代器建立 ndarray
x=np.fromiter(it, dtype=float)
print(x)

#### numpy從數值範圍生成數組dom

  1. numpy.arange(start, end, step, dtype)
  2. numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) #建立一個一維數組,數組是一個等差數列構成的
  3. np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None) #函數用於建立一個於等比數列

#### Numpy--結構化數據類型函數

  • numpy中支持不少數據類型,好比int,float等,也能夠本身使用dtype()本身新定義一個數據類型,這個數據類型可能相似於C中的數據結構。
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

  1. 整數數組索引
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]]
'''

- numpy迭代器****

  1. **np.nditer(order, op_flags, flags) ** #默認行遍歷優先,order遍歷順序,op_flags控制列表是否可讀寫,flags外部循環
#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],
相關文章
相關標籤/搜索