Numpy学习---Task03---数组的操作
task03---數組的操作
1)更改形狀
? 在對數組進行操作時,為了滿足格式和計算的要求通常會改變其形狀。
?`numpy.ndarray.shape`
? 表示數組的維度,返回一個元組,這個元組的長度就是維度的數目,即 `ndim` 屬性(秩)。
import numpy as npx = np.array([1, 2, 9, 4, 5, 6, 7, 8]) print(x.shape) # (8,) x.shape = [2, 4] print(x) # [[1 2 9 4] # [5 6 7 8]]`numpy.ndarray.flat`
將數組轉換為一維的迭代器,可以用for訪問數組每一個元素。
import numpy as npx = np.array([[11, 12, 13, 14, 15],[16, 17, 18, 19, 20],[21, 22, 23, 24, 25],[26, 27, 28, 29, 30],[31, 32, 33, 34, 35]]) y = x.flat print(y) # <numpy.flatiter object at 0x0000020F9BA10C60> for i in y:print(i, end=' ') # 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35y[3] = 0 print(end='\n') print(x) # [[11 12 13 0 15] # [16 17 18 19 20] # [21 22 23 24 25] # [26 27 28 29 30] # [31 32 33 34 35]]? ? ? ? 忽然發現在對x進行.flat函數處理后,y內保存的地址在經過for循環打印輸出一次之后無法再次實現打印輸出。緣由目前我還不是很清楚。需要向其他大佬請教一下,回頭解釋。
`numpy.ndarray.flatten([order='C'])`
將數組的副本轉換為一維數組,并返回。
- ndarray.flatten(order='C')
- Return a copy of the array collapsed into one dimension.
Parameters:? order?: {‘C’, ‘F’, ‘A’, ‘K’}, optional
‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if?a?is Fortran?contiguous?in memory, row-major order otherwise. ‘K’ means to flatten?a?in the order the elements occur in memory. The default is ‘C’.
Returns: A copy of the input array, flattened to one dimension
.
`numpy.ravel(a, order='C')`
- Return a contiguous flattened array.
- order='C'時返回的是視圖;
- order=’F‘ 時是拷貝。
`numpy.reshape(a, newshape[, order='C'])`
- ?在不更改數據的情況下為數組賦予新的形狀。
?`reshape()`函數當參數`newshape = [rows,-1]`時,將根據行數自動確定列數。
x = np.arange(10) y = np.reshape(x,[2,5]) print(y.dtype) print(y)#int32 #[[0 1 2 3 4] # [5 6 7 8 9]]y = np.reshape(x,[2,-1]) print(y)#[[0 1 2 3 4] # [5 6 7 8 9]]y = np.reshape(x,[-1,2]) print(y)#[[0 1] # [2 3] # [4 5] # [6 7] # [8 9]]y[0,0] = 10 print(x)#[10 1 2 3 4 5 6 7 8 9](改變x去reshape后y中的值,x對應元素也改變)`reshape()`函數當參數`newshape = -1`時,表示將數組降為一維。
x = np.random.randint(1,100,[2,2,3]) print(x) y = np.reshape(x,-1) print(y)#[[[47 76 25] # [52 66 34]] # # [[29 76 56] # [25 67 60]]] #[47 76 25 52 66 34 29 76 56 25 67 60]2)更改維度
`numpy.newaxis = None`
- ?`None`的別名,對索引數組很有用。
? ? ? ?很多工具包在進行計算時都會先判斷輸入數據的維度是否滿足要求,如果輸入數據達不到指定的維度時,可以使用`newaxis`參數來增加一個維度。
x = np.array([1,2,3,4,5,6,7,8,9]) print(x.shape) print(x)#(9,) #[1 2 3 4 5 6 7 8 9]y = x[np.newaxis,:] print(y.shape) print(y)#(1, 9) #[[1 2 3 4 5 6 7 8 9]]y = x[:,np.newaxis] print(y.shape) print(y)#(9, 1) #[[1] # [2] # [3] # [4] # [5] # [6] # [7] # [8] # [9]]`numpy.squeeze(a, axis=None)`?
- ? `a`表示輸入的數組;
- ? `axis`用于指定需要刪除的維度,但是指定的維度必須為單維度,否則將會報錯
? ? ? ? 在機器學習和深度學習中,通常算法的結果是可以表示向量的數組(即包含兩對或以上的方括號形式[[]]),如果直接利用這個數組進行畫圖可能顯示界面為空(見后面的示例)。我們可以利用`squeeze()`函數將表示向量的數組轉換為秩為1的數組,這樣利用 matplotlib 庫函數畫圖時,就可以正常的顯示結果了。
import matplotlib.pyplot as plt x = np.array([[1,1,2,3,5,8,13,21]]) print(x.shape) plt.plot(x) plt.show()(1, 8)
x = np.squeeze(x) print(x.shape) plt.plot(x) plt.show()(8,)
3)數組組合
`numpy.concatenate((a1, a2, ...), axis=0, out=None)`
- Join a sequence of arrays along an existing axis.
`numpy.stack(arrays, axis=0, out=None)`
- Join a sequence of arrays along a new axis.
`numpy.hstack(tup)`
- Stack arrays in sequence horizontally (column wise).?
操作數.ndim > 1時等價于np.concatenate((a1, a2, ...), axis=1), 操作數.ndim = 1時則可視作np.concatenate((a1, a2, ...), axis=0)
?
注:操作數為一維數組時.hstack并不完全等價于.concatenate
a = np.hstack([np.array([1, 2, 3, 4]), 5]) print(a) # [1 2 3 4 5]a = np.concatenate([np.array([1, 2, 3, 4]), 5]) print(a)# all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 0 dimension(s)`numpy.vstack(tup)`
- Stack arrays in sequence vertically (row wise).
操作數.ndim > 1時等價于np.concatenate((a1, a2, ...), axis=1),操作數.ndim =1時等價于np.stack(arrays, axis=0, out=None)
x = np.array([1,2,3]) y = np.array([4,5,6])z = np.vstack([x,y]) print(z)#[[1 2 3] # [4 5 6]]z = np.stack([x,y]) print(z)#[[1 2 3] # [4 5 6]]x = np.random.randint(0,10,(3,3)) y = np.random.randint(0,10,(3,3)) print(x) print(y)#[[8 8 0] # [4 2 6] # [3 0 7]]#[[0 0 1] # [4 0 0] # [0 3 1]]z = np.vstack([x,y]) print(z)#[[8 8 0] # [4 2 6] # [3 0 7] # [0 0 1] # [4 0 0] # [0 3 1]]z = np.concatenate([x,y]) print(z)#[[8 8 0] # [4 2 6] # [3 0 7] # [0 0 1] # [4 0 0] # [0 3 1]]4)數組拆分
`numpy.split(ary, indices_or_sections, axis=0)`?
- Split an array into multiple sub-arrays as views into ary.
`numpy.vsplit(ary, indices_or_sections)`?
- Split an array into multiple sub-arrays vertically (row-wise).
`numpy.hsplit(ary, indices_or_sections)`
- Split an array into multiple sub-arrays horizontally (column-wise).
5)數組展平
`numpy.tile(A, reps)`
- Construct an array by repeating A the number of times given by reps.
- 'tile'是平鋪或并列顯示的意思
`numpy.repeat(a, repeats, axis=None)`?
- Repeat elements of an array.
- `axis=0`,沿著y軸復制,實際上增加了行數。
- `axis=1`,沿著x軸復制,實際上增加了列數。
- `repeats`,可以為一個數,也可以為一個矩陣。
- `axis=None`時就會flatten當前矩陣,實際上就是變成了一個行向量。
6)添加和刪除元素
numpy.insert(arr, obj, values, axis=None)
#參數axis為默認值時會將arr展平后進行insert操作x = np.array([[1,2],[3,4]]) print(x)#[[1 2] # [3 4]]y = np.insert(x,2,5) print(y)#[1 2 5 3 4]#參數values與arr中的元素數據類型不同時,values會自動轉換為arr中元素的類型y = np.insert(x,2,5.0) print(y)#[1 2 5 3 4]#multiple insertionnsy = np.insert(x,[2,3],5) print(y)#[1 2 5 3 5 4]y = np.insert(x,[1,2],[5,6],axis=0) print(y)#[[1 2] # [5 6] # [3 4] # [5 6]]y = np.insert(x,[1,2],[5,6],axis=1) print(y)#[[1 5 2 6] # [3 5 4 6]]numpy.delete(arr, obj, axis=None)
#參數axis為默認值時會將arr展平后進行delete操作x = np.array([[1,2],[3,4]]) print(x)#[[1 2] # [3 4]]y = np.delete(x,1) print(y)#[1 3 4]y = np.delete(x,(1,2)) print(y)#[1 4]y = np.delete(x,1,axis=0) print(y)#[[1 2]]y = np.delete(x,1,axis=1) print(y)#[[1] # [3]]7)查找元素
`numpy.unique(ar, return_index=False, return_inverse=False,return_counts=False, axis=None)`?
- Find the unique elements of an array.
- return_index:the indices of the input array that give the unique values
- return_inverse:the indices of the unique array that reconstruct the input array
- return_counts:the number of times each unique value comes up in the input array
總結
以上是生活随笔為你收集整理的Numpy学习---Task03---数组的操作的全部內容,希望文章能夠幫你解決所遇到的問題。