1.修改數組的形狀
- reshape :不改變數據
- flat : 數組迭代器
- flatten: 返回一份數據拷貝
- ravel: 返回展開的數組
flat迭代器的使用:
for element in a.flat:
print(element)
flatten:返回一份拷貝的數據:
ndarry.flatten(order='C') #order可選
reval展開數組:
ndarray.reval(order='C‘) #order可選
2.翻轉數組
- transpose 對換數組維度
- ndarray.T 與transpose相同
- rollaxis 向后滑動指定的軸
- swapaxes 對換數組的兩個軸
import numpy as np a=np.arange(12).reshape(3,4) print('原數組') print(a) print('轉置數組') print(a.T)
運算結果:
原數組 [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] 轉置數組 [[ 0 4 8] [ 1 5 9] [ 2 6 10] [ 3 7 11]] Process finished with exit code 0
* numpy.rollaxis 函數向后滾動特定的軸到一個特定位置,格式如下:
numpy.rollaxis(arr,axis,start)
arr
:數組axis
:要向后滾動的軸,其它軸的相對位置不會改變start
:默認為零,表示完整的滾動。會滾動到特定位置。
numpy.swapaxes
用於轉換數組的兩個軸,格式如下:
numpy.swapaxes(arr,axis1,axis2)
arr
:輸入的數組axis1
:對應第一個軸的整數axis2
:對應第二個軸的整數
numpy.broadcast
numpy.broadcast 用於模仿廣播的對象,它返回一個對象,該對象封裝了將一個數組廣播到另一個數組的結果。
該函數使用兩個數組作為輸入參數,如下實例:
x=np.array([[1],[2],[3])
y=np.array([4,5,6])
b=np.broadcast(x,y) #對x y 進行廣播,並且擁有自身組件的迭代器元組
r,c=b.iters
print(next(r),next(c)) #對x y進行廣播
print(shape) #返回廣播對象的形狀
numpy.expend_dims
該函數通過在指定位置插入新的軸來擴展數組的形狀:
numpy.expend_dims(arr,axis)
arr:輸入數組
axis:新軸插入的位置
numpy.squeeze 函數從給定數組的形狀中刪除一維的條目,函數格式如下:
numpy.squeeze(arr, axis)
arr
:輸入數組axis
:整數或整數元組,用於選擇形狀中一維條目的子集
3.連接數組
concatenate : 連接沿着現有軸數組的序列
stack : 沿着新的軸加入一系列數組
hstack: 水平堆疊序列中的數組
vstack: 垂直堆疊序列中的數組
例如對於 a b 兩個數組
print (np.concatenate((a,b))) #'沿軸 Y 連接兩個數組
print (np.concatenate((a,b),axis = 1))#'沿軸 X 連接兩個數組
4.分割數組
split: 將一個數組分割為多個子數組
hsplit: 將一個數組水平分割為多個子數組(按列)
vsplit: 將一個數組垂直分割為多個子數組(按行)
5.數組元素的添加與刪除
resize 返回指定形狀的新數組
append 將值添加到末尾
insert 沿着指定的軸將值插入到指定下標之下
delete 刪除某個軸的子數組,並返回刪除后的新數組
unique 查找數組內的唯一元素
resize的應用:
格式:numpy.resize(arr, shape)
b = np.resize(a,(3,3)) print (b)
append的應用:格式:numpy.append(arr, values, axis=None)print
(np.append(a, [7,8,9]))#像數組a添加元素
(np.append(a,[[7,8,9]],axis=0) #沿着Y軸添加元素
insert的應用: 格式:numpy.insert(arr,obj,values,axis)
print (np.insert(a,3,[11,12])) 就是指在數組a的下標3上插入數組[11,12]d
delect的應用:
Numpy.delete(arr, obj, axis)
arr
:輸入數組obj
:可以被切片,整數或者整數數組,表明要從輸入數組刪除的子數組axis
:沿着它刪除給定子數組的軸,如果未提供,則輸入數組會被展開
如刪除數組a的第二列: np.delete(a,1,axis = 1))
a=np.arange(12).reshape(3,4)
print('原數組')
print(a)
print('\n') print(np.delete(a,1,axis = 0))
運行結果:
原數組
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[ 0 1 2 3] [ 8 9 10 11]] Process finished with exit code 0
np.delete(a,1,axis = 0)中是對第二行進行刪除操作
numpy.unique
去除數組中的重復元素
numpy.unique(arr,return_index,return_inverse,return_counts)
arr
:輸入數組,如果不是一維數組則會展開return_index
:如果為true
,返回新列表元素在舊列表中的位置(下標),並以列表形式儲return_inverse
:如果為true
,返回舊列表元素在新列表中的位置(下標),並以列表形式儲return_counts
:如果為true
,返回去重數組中的元素在原數組中的出現次數
# 去除數組中重復的元素 unique
au = np.array([5, 2, 6, 2, 7, 5, 6, 8, 2, 9])
u=np.unique(au)
u,indices=np.unique(au,return_inverse=True)
print(u)
print('\n')
print(indices)
運行結果:
[2 5 6 7 8 9] [1 0 2 0 3 1 2 4 0 5] Process finished with exit code 0