numpy中的降维方法:
- flat():返回一个iterator,然后去遍历
- flatten():将多维数组拉平,并拷贝一份
- ravel():将多维数组拉平(一维)
- squeeze():除开发者_Go培训去多维数组中,维数为1的维度,如315降维后3*5
- reshape(-1):多维数组,拉平
- reshape(-1,5),其中-1表示我们不用亲自去指定这一维度的大小,理解为n维
代码示例:
import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) c = [] for x in a.flat: c.append(x) print('flat迭代器降一维:\n', c) d = a.flatphpten() print('flatten方法降一维:\n', d) e = a.ravel() print('ravel方法降一维:\n', e) g = np.squeeze(a) print('squeeze方法降一维:\n', g) f = a.reshape(-1) print('reshape方法降一维:\n', f) a.resize((1, 6)) print('resize方法:\n', a)
结果:
flat迭代器降一维:
[1, 2, 3, 4, 5, 6]flatten方法降一维:[1 2 3 4 5 6]ravel方法降一维:[1 2 3 4 5 6]squeeze方法降一维:[[1 2 3][4 5 6]]reshape方法降一维:[1 2 3 4 5 6]resize方法:[[1 2 3 4 5 6]]
补:NumPy 高维数组降维方法
import numpy as np a = np.arange(64).reshape([4,4,4]) # [[[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 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] # [36 37 38 39] # [40 41 42 43] # [44 45 46 47]] # # [[48 49 50 51] # [52 53 54 55] # [56 57 58 59] # [60 61 62 63]]] print(a) # 对三维数组a进行降维打击 a_reshape = a.reshape(-1) # [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 # 24 25 26 http://www.devze.com27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 # 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63] print('reshape方法:\n',a_reshape) c_flat = [] for x in a.flat: c_flat.append(x) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 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, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53http://www.devze.com, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63] print('flat迭代器:\n',c_flat) d_flatten = a.flatten() # [0 1 2 3 4 5 6 7 8 9 10 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 36 37 38 39 40 41 42 43 44 45 46 47 # 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63] print('flatten方法:\n',d_flatten) e_ravel = a.ravel() # [ 0 1 2 3 4 5 6 7 8 9 10 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 3www.devze.com6 37 38 39 40 41 42 43 44 45 46 47 # 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63] print('ravel方法:\n',e_ravel) f_resize = a.resize(64) # None resize 没有返回值,改变的是原数组 print('resize方法:\n',f_resize) # [python 0 1 2 3 4 5 6 7 8 9 10 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 36 37 38 39 40 41 42 43 44 45 46 47 # 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63] print(a)
到此这篇关于numpy降维方法的文章就介绍到这了,更多相关numpy 降维内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
精彩评论